package com.logos.musicframe.ui.javafx;

import com.logos.musicframe.constant.TimeConstant;
import com.logos.musicframe.controller.PlaylistCollectedController;
import com.logos.musicframe.controller.PlaylistController;
import com.logos.musicframe.controller.SongsController;
import com.logos.musicframe.controller.SongsLikedController;
import com.logos.musicframe.controller.SongsPlaylistController;
import com.logos.musicframe.controller.UsersController;
import com.logos.musicframe.controller.ChatController;
import com.logos.musicframe.controller.ChatHistoryController;
import com.logos.musicframe.req.ChatReq;
import com.logos.musicframe.resp.MsgResp;
import com.logos.musicframe.constant.RedisConstant;
import com.logos.musicframe.resp.PlaylistResp;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.resp.UsersResp;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.ui.javafx.LikesPageUi;
import com.logos.musicframe.ui.javafx.PersonalCenterUi;
import com.logos.musicframe.ui.javafx.PlaylistUi;
import com.logos.musicframe.ui.javafx.RecentPlayPageUi;
import com.logos.musicframe.utils.JavaFxMusicPlayer;
import com.logos.musicframe.utils.LocalSessionStorageUtil;
import com.logos.musicframe.utils.RedisUtil;
import com.logos.musicframe.utils.SpringContextUtil;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Popup;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javafx.application.Platform;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author logos
 * date 2025/6/13 15:55
 * @version v1.0
 * @Package com.logos.musicframe.ui
 */
@Component
@Lazy
@Slf4j
public class MainMusicPlayerUi extends Application {

    private Scene scene;
    private VBox rightPanel;
    private VBox leftPanel;
    private BorderPane root;

    private HBox playerBar;

    private ImageView currentSongImageView = new ImageView();


    private SongsResp currentSong;

    private SongsLikedController songsLikedController = SpringContextUtil.getBean(SongsLikedController.class);

    private JavaFxMusicPlayer player = SpringContextUtil.getBean(JavaFxMusicPlayer.class);

    private RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);

    private UsersController usersController = SpringContextUtil.getBean(UsersController.class);

    private SongsController songsController = SpringContextUtil.getBean(SongsController.class);
    
    private PlaylistController playlistController = SpringContextUtil.getBean(PlaylistController.class);
    
    private PlaylistCollectedController playlistCollectedController = SpringContextUtil.getBean(PlaylistCollectedController.class);

    private SongsPlaylistController songsPlaylistController = SpringContextUtil.getBean(SongsPlaylistController.class);
    
    private ChatController chatController = SpringContextUtil.getBean(ChatController.class);

    // 歌词内容
    private VBox lyricsView;
    private boolean isShowingLyrics = false;
    private VBox mainContentView;

    // 用于存储解析后的歌词
    private List<LyricLine> parsedLyrics = new ArrayList<>();
    private int currentHighlightIndex = -1;
    // 时间更新定时器
    private Timeline lyricUpdateTimeline;

    // 主页刷新定时器
    private Timeline homePageRefreshTimeline;
    private List<SongsResp> currentDaySongs = new ArrayList<>();
    private GridPane daySongsGrid;

    @Override
    public void start(Stage primaryStage) {
        root = new BorderPane();

        // 初始化左侧面板
        leftPanel = createLeftPanel();
        root.setLeft(leftPanel);

        // 初始化右侧面板
        rightPanel = createRightPanel();
        // 存储主内容视图引用
        mainContentView = rightPanel;
        root.setCenter(rightPanel);

        // 添加顶部搜索栏
        root.setTop(createTopSearchBar());

        // 创建场景
        scene = new Scene(root, 1200, 800);
        primaryStage.setScene(scene);

        // 设置图标
        primaryStage.getIcons().add(new Image("static/logo.png"));

        // 添加窗口关闭事件处理
        primaryStage.setOnCloseRequest(event -> {
            log.info("应用程序正在关闭...");
            // 停止所有正在运行的任务和线程
            stopLyricUpdateTimer();
            stopHomePageRefreshTimer();
            // 停止播放器
            if (player != null) {
                player.stop();
            }
            // 关闭Spring上下文
            Platform.exit();
            System.exit(0);
        });

        primaryStage.show();

        // 默认显示主页
        showHomePage();

        // 添加播放条
        playerBar = createMusicPlayerBar();
        root.setBottom(playerBar);
        
        // 启动主页自动刷新
        startHomePageRefreshTimer();
        
        // 添加自动播放下一首的监听器
        player.addPlayerStatusListener(new JavaFxMusicPlayer.PlayerAutoNextListener() {
            @Override
            public void onAutoPlayNext(int currentIndex) {
                // 在JavaFX线程中更新UI
                Platform.runLater(() -> updateCurrentSongFromPlaylist());
            }
            
            @Override
            public void onPlayerStatusChanged(MediaPlayer mediaPlayer) {
                // 已由基本监听器处理
            }
        });
    }

    private HBox createMusicPlayerBar() {
        playerBar = new HBox();
        playerBar.setSpacing(15);
        playerBar.setPadding(new Insets(10, 20, 10, 20));
        playerBar.setAlignment(Pos.CENTER);
        // 设置渐变背景色和阴影效果，使用更柔和的配色方案
        playerBar.setStyle("-fx-background-color: linear-gradient(to right, #f0f0f2, #e8e8f0, #f0f0f2); " +
                          "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 8, 0, 0, 3); " +
                          "-fx-padding: 15px;");

        // 左侧：歌曲信息区域
        HBox songInfoBox = new HBox(10);
        songInfoBox.setAlignment(Pos.CENTER_LEFT);
        songInfoBox.setPrefWidth(250);

        // 歌曲封面 - 添加圆角和阴影
        StackPane coverContainer = new StackPane();
        currentSongImageView.setFitWidth(50);
        currentSongImageView.setFitHeight(50);
        
        // 设置圆角
        Rectangle clip = new Rectangle(50, 50);
        clip.setArcWidth(10);
        clip.setArcHeight(10);
        currentSongImageView.setClip(clip);
        
        // 添加阴影效果
        currentSongImageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.3), 5, 0, 0, 2);");
        coverContainer.getChildren().add(currentSongImageView);
        
        // 添加鼠标点击事件
        currentSongImageView.setOnMouseClicked(event -> {
            if (currentSong != null) {
                toggleLyricsView();
            }
        });
        // 添加鼠标悬停效果
        currentSongImageView.setOnMouseEntered(e -> {
            currentSongImageView.setStyle("-fx-cursor: hand; -fx-effect: dropshadow(three-pass-box, rgba(29,185,84,0.5), 8, 0, 0, 3);");
            currentSongImageView.setOpacity(0.8);
        });
        currentSongImageView.setOnMouseExited(e -> {
            currentSongImageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.3), 5, 0, 0, 2);");
            currentSongImageView.setOpacity(1.0);
        });

        // 歌曲和歌手信息 - 改进文字样式
        VBox songDetails = new VBox(2);
        Label songTitle = new Label("未知歌曲");
        songTitle.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #333333;");
        Label artistName = new Label("未知歌手");
        artistName.setStyle("-fx-font-size: 12px; -fx-text-fill: #666666;");
        songDetails.getChildren().addAll(songTitle, artistName);

        // 喜欢按钮 - 改进样式
        Button likeButton = new Button();
        ImageView likeIcon;
        
        // 检查当前歌曲是否已点赞
        if (currentSong != null && currentSong.getIsLiked() != null && currentSong.getIsLiked()) {
            likeIcon = new ImageView(new Image("static/heart-filled.png", 20, 20, true, true));
        } else {
            likeIcon = new ImageView(new Image("static/heart-icon.png", 20, 20, true, true));
        }
        
        likeButton.setGraphic(likeIcon);
        likeButton.setStyle("-fx-background-color: transparent; -fx-padding: 5px; -fx-background-radius: 50%;");
        likeButton.setOnMouseEntered(e -> likeButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 5px; -fx-background-radius: 50%;"));
        likeButton.setOnMouseExited(e -> likeButton.setStyle("-fx-background-color: transparent; -fx-padding: 5px; -fx-background-radius: 50%;"));
        
        // 添加点击事件，切换当前歌曲的喜欢状态
        likeButton.setOnAction(event -> {
            if (currentSong != null) {
                boolean isCurrentlyLiked = currentSong.getIsLiked() != null && currentSong.getIsLiked();
                
                // 调用切换喜欢状态的方法
                new Thread(() -> {
                    try {
                        Result<Boolean> actionResult;
                        
                        if (isCurrentlyLiked) {
                            // 如果当前已喜欢，则取消喜欢
                            actionResult = songsLikedController.unlike(currentSong.getId());
                            log.info("取消喜欢歌曲: {}", currentSong.getId());
                        } else {
                            // 如果当前未喜欢，则添加喜欢
                            actionResult = songsLikedController.like(currentSong.getId());
                            log.info("喜欢歌曲: {}", currentSong.getId());
                        }
                        
                        // 操作成功，更新按钮状态和歌曲喜欢状态
                        if (actionResult.isSuccess()) {
                            // 更新歌曲对象的喜欢状态
                            currentSong.setIsLiked(!isCurrentlyLiked);
                            
                            Platform.runLater(() -> {
                                ImageView newIcon;
                                if (!isCurrentlyLiked) {
                                    newIcon = new ImageView(new Image("static/heart-filled.png", 20, 20, true, true));
                                } else {
                                    newIcon = new ImageView(new Image("static/heart-icon.png", 20, 20, true, true));
                                }
                                likeButton.setGraphic(newIcon);
                            });
                        }
                    } catch (Exception e) {
                        log.error("切换歌曲喜欢状态失败", e);
                    }
                }).start();
            }
        });

        // 评论按钮
        Button commentButton = new Button();
        ImageView commentIcon = new ImageView(new Image("static/comment-icon.png", 20, 20, true, true));
        commentButton.setGraphic(commentIcon);
        commentButton.setStyle("-fx-background-color: transparent; -fx-padding: 5px; -fx-background-radius: 50%;");
        commentButton.setOnMouseEntered(e -> commentButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 5px; -fx-background-radius: 50%;"));
        commentButton.setOnMouseExited(e -> commentButton.setStyle("-fx-background-color: transparent; -fx-padding: 5px; -fx-background-radius: 50%;"));

        // 更多按钮
        Button moreButton = new Button();
        ImageView moreIcon = new ImageView(new Image("static/more-icon.png", 20, 20, true, true));
        moreButton.setGraphic(moreIcon);
        moreButton.setStyle("-fx-background-color: transparent; -fx-padding: 5px; -fx-background-radius: 50%;");
        moreButton.setOnMouseEntered(e -> moreButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 5px; -fx-background-radius: 50%;"));
        moreButton.setOnMouseExited(e -> moreButton.setStyle("-fx-background-color: transparent; -fx-padding: 5px; -fx-background-radius: 50%;"));

        songInfoBox.getChildren().addAll(coverContainer, songDetails, likeButton, commentButton, moreButton);

        // 中间：播放控制区域
        HBox controlBox = new HBox(15);
        controlBox.setAlignment(Pos.CENTER);

        // 循环模式按钮（替代原来的随机播放按钮）
        Button repeatButton = new Button();
        ImageView repeatIcon = new ImageView(new Image("static/reservation_repeat_icon.png", 20, 20, true, true));
        repeatButton.setGraphic(repeatIcon);
        repeatButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
        repeatButton.setTooltip(new Tooltip("列表循环"));
        
        // 设置循环模式（默认为列表循环）
        final int[] repeatMode = {0}; // 0: 列表循环, 1: 单曲循环, 2: 随机播放
        
        // 点击切换循环模式
        repeatButton.setOnAction(e -> {
            repeatMode[0] = (repeatMode[0] + 1) % 3;
            updateRepeatButtonIcon(repeatButton, repeatMode[0]);
            
            // 设置播放器的循环模式
            switch (repeatMode[0]) {
                case 0: // 列表循环
                    player.setRepeatMode(JavaFxMusicPlayer.RepeatMode.PLAYLIST);
                    break;
                case 1: // 单曲循环
                    player.setRepeatMode(JavaFxMusicPlayer.RepeatMode.SINGLE);
                    break;
                case 2: // 随机播放
                    player.setRepeatMode(JavaFxMusicPlayer.RepeatMode.SHUFFLE);
                    break;
            }
        });
        
        repeatButton.setOnMouseEntered(e -> {
            repeatButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 8px; -fx-background-radius: 50%;");
            repeatIcon.setOpacity(1.0);
        });
        repeatButton.setOnMouseExited(e -> {
            repeatButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
            if (repeatMode[0] == 0) {
                repeatIcon.setOpacity(0.7);
            }
        });
        repeatIcon.setOpacity(0.7);

        // 上一首按钮
        Button previousButton = new Button();
        ImageView previousIcon = new ImageView(new Image("static/prev-icon.png", 24, 24, true, true));
        previousButton.setGraphic(previousIcon);
        previousButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
        previousButton.setOnMouseEntered(e -> {
            previousButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 8px; -fx-background-radius: 50%;");
            previousIcon.setOpacity(1.0);
        });
        previousButton.setOnMouseExited(e -> {
            previousButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
            previousIcon.setOpacity(0.7);
        });
        previousIcon.setOpacity(0.7);
        previousButton.setOnAction(event -> {
            // 播放上一首歌曲
            if (player.playPrevious()) {
                // 更新当前歌曲信息
                updateCurrentSongFromPlaylist();
            } else {
                log.info("无法播放上一首歌曲");
            }
        });

        // 播放/暂停按钮 - 使用绿色圆形背景
        Button playPauseButton = new Button();
        ImageView playPauseIcon = new ImageView(new Image("static/pause-icon.png", 24, 24, true, true));
        playPauseButton.setGraphic(playPauseIcon);
        playPauseButton.setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-background-radius: 50%; " +
                "-fx-padding: 12px; " +
                "-fx-effect: dropshadow(three-pass-box, rgba(29,185,84,0.5), 8, 0, 0, 0);"
        );
        playPauseButton.setOnMouseEntered(e -> 
            playPauseButton.setStyle(
                "-fx-background-color: #1ed760; " +
                "-fx-background-radius: 50%; " +
                "-fx-padding: 12px; " +
                "-fx-effect: dropshadow(three-pass-box, rgba(29,185,84,0.6), 10, 0, 0, 0);"
            )
        );
        playPauseButton.setOnMouseExited(e -> 
            playPauseButton.setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-background-radius: 50%; " +
                "-fx-padding: 12px; " +
                "-fx-effect: dropshadow(three-pass-box, rgba(29,185,84,0.5), 8, 0, 0, 0);"
            )
        );
        playPauseButton.setOnAction(event -> {
            if (player.isPlaying) {
                player.pause();
                playPauseIcon.setImage(new Image("static/play-icon.png", 24, 24, true, true));
            } else if (currentSong != null) {
                player.play(currentSong.getFilePath());
                playPauseIcon.setImage(new Image("static/pause-icon.png", 24, 24, true, true));
                // 更新当前歌曲信息
                updateCurrentSongInfo(currentSong);
            }
        });

        // 下一首按钮
        Button nextButton = new Button();
        ImageView nextIcon = new ImageView(new Image("static/next-icon.png", 24, 24, true, true));
        nextButton.setGraphic(nextIcon);
        nextButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
        nextButton.setOnMouseEntered(e -> {
            nextButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 8px; -fx-background-radius: 50%;");
            nextIcon.setOpacity(1.0);
        });
        nextButton.setOnMouseExited(e -> {
            nextButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
            nextIcon.setOpacity(0.7);
        });
        nextIcon.setOpacity(0.7);
        nextButton.setOnAction(event -> {
            // 播放下一首歌曲
            if (player.playNext()) {
                // 更新当前歌曲信息
                updateCurrentSongFromPlaylist();
            } else {
                log.info("无法播放下一首歌曲");
            }
        });



        controlBox.getChildren().addAll(repeatButton, previousButton, playPauseButton, nextButton);

        // 右侧：进度条和音量控制
        VBox progressBox = new VBox(5);
        progressBox.setAlignment(Pos.CENTER);
        progressBox.setPrefWidth(400);

        // 时间和进度条
        HBox timeBox = new HBox(10);
        timeBox.setAlignment(Pos.CENTER);
        timeBox.setPrefWidth(400);

        // 当前时间
        Label currentTimeLabel = new Label("00:00");
        currentTimeLabel.setStyle("-fx-text-fill: #555555; -fx-font-size: 12px;");

        // 进度条 - 改进样式
        Slider progressSlider = new Slider(0, 100, 0);
        progressSlider.setPrefWidth(300);
        progressSlider.setStyle(
                "-fx-control-inner-background: #d0d0d5; " +
                "-fx-accent: #1db954; " +
                "-fx-background-radius: 2px; " +
                "-fx-padding: 2px;"
        );
        HBox.setHgrow(progressSlider, Priority.ALWAYS);

        // 总时长
        Label totalTimeLabel = new Label("00:00");
        totalTimeLabel.setStyle("-fx-text-fill: #555555; -fx-font-size: 12px;");

        timeBox.getChildren().addAll(currentTimeLabel, progressSlider, totalTimeLabel);
        progressBox.getChildren().add(timeBox);

        // 进度条拖动事件
        progressSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            // 只有在用户拖动时才处理，避免与自动更新冲突
            if (progressSlider.isValueChanging() && player.getMediaPlayer() != null) {
                // 计算拖动到的时间点
                double totalDuration = player.getTotalDuration().toSeconds();
                if (totalDuration > 0) {
                    double seekTime = newVal.doubleValue() * totalDuration / 100;
                    player.seek(seekTime);
                }
            }
        });

        // 鼠标释放时的事件处理
        progressSlider.setOnMouseReleased(event -> {
            if (player.getMediaPlayer() != null && !player.getMediaPlayer().getStatus().equals(MediaPlayer.Status.STOPPED)) {
                double value = progressSlider.getValue();
                double totalDuration = player.getTotalDuration().toSeconds();
                if (totalDuration > 0) {
                    double seekTime = value * totalDuration / 100;
                    player.seek(seekTime);
                }
            }
        });

        // 音量控制按钮 - 改进样式
        Button volumeButton = new Button();
        ImageView volumeIcon = new ImageView(new Image("static/volume.png", 20, 20, true, true));
        volumeButton.setGraphic(volumeIcon);
        volumeButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;");
        volumeButton.setOnMouseEntered(e -> volumeButton.setStyle("-fx-background-color: rgba(255,255,255,0.1); -fx-padding: 8px; -fx-background-radius: 50%;"));
        volumeButton.setOnMouseExited(e -> volumeButton.setStyle("-fx-background-color: transparent; -fx-padding: 8px; -fx-background-radius: 50%;"));

        // 创建音量控制滑块和弹出窗口
        Slider volumeSlider = new Slider(0, 1, 0.5); // 音量范围0-1，默认0.5
        volumeSlider.setPrefWidth(100);
        volumeSlider.setStyle(
                "-fx-control-inner-background: #d0d0d5; " +
                "-fx-accent: #1db954; " +
                "-fx-background-radius: 2px; " +
                "-fx-padding: 2px;"
        );

        // 创建弹出窗口容器
        VBox volumePopup = new VBox(10);
        volumePopup.setPadding(new Insets(10));
        volumePopup.setStyle(
                "-fx-background-color: #f5f5f7; " +
                "-fx-border-color: #e0e0e5; " +
                "-fx-border-radius: 5px; " +
                "-fx-background-radius: 5px; " +
                "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 0);"
        );

        // 添加音量控制UI（包含-/+符号和滑块）
        HBox volumeControlBox = new HBox(5);
        volumeControlBox.setAlignment(Pos.CENTER);

        // 减小音量按钮
        Button minusButton = new Button("-");
        minusButton.setStyle(
                "-fx-font-weight: bold; " +
                "-fx-background-color: transparent; " +
                "-fx-text-fill: #555555; " +
                "-fx-padding: 2px 5px;"
        );
        minusButton.setOnAction(e -> {
            double currentVolume = volumeSlider.getValue();
            if (currentVolume >= 0.1) {
                volumeSlider.setValue(currentVolume - 0.1);
            } else {
                volumeSlider.setValue(0);
            }
        });

        // 增大音量按钮
        Button plusButton = new Button("+");
        plusButton.setStyle(
                "-fx-font-weight: bold; " +
                "-fx-background-color: transparent; " +
                "-fx-text-fill: #555555; " +
                "-fx-padding: 2px 5px;"
        );
        plusButton.setOnAction(e -> {
            double currentVolume = volumeSlider.getValue();
            if (currentVolume <= 0.9) {
                volumeSlider.setValue(currentVolume + 0.1);
            } else {
                volumeSlider.setValue(1.0);
            }
        });

        // 音量百分比显示标签
        Label volumeValueLabel = new Label("50%");
        volumeValueLabel.setPrefWidth(35);
        volumeValueLabel.setStyle("-fx-font-size: 11px; -fx-text-fill: #555555; -fx-text-alignment: center;");

        // 更新音量标签随滑块变化
        volumeSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (player != null && player.getMediaPlayer() != null) {
                // 设置音量
                player.setVolume(newVal.doubleValue());
                
                // 更新音量百分比显示
                int volumePercent = (int) (newVal.doubleValue() * 100);
                volumeValueLabel.setText(volumePercent + "%");
                
                // 根据音量值更新图标
                if (newVal.doubleValue() == 0) {
                    volumeButton.setGraphic(new ImageView(new Image("static/volume-mute.png", 20, 20, true, true)));
                } else if (newVal.doubleValue() < 0.5) {
                    volumeButton.setGraphic(new ImageView(new Image("static/volume-low.png", 20, 20, true, true)));
                } else {
                    volumeButton.setGraphic(new ImageView(new Image("static/volume.png", 20, 20, true, true)));
                }
            }
        });

        // 将所有组件添加到音量控制器中
        volumeControlBox.getChildren().addAll(minusButton, volumeSlider, plusButton);
        volumePopup.getChildren().addAll(volumeControlBox, volumeValueLabel);
        VBox.setMargin(volumeValueLabel, new Insets(5, 0, 0, 0));
        HBox.setHgrow(volumeValueLabel, Priority.NEVER);
        volumeValueLabel.setAlignment(Pos.CENTER);

        // 创建弹出窗口
        Popup popup = new Popup();
        popup.getContent().add(volumePopup);
        // 点击其他区域自动隐藏
        popup.setAutoHide(true);

        // 为音量按钮添加点击事件，显示/隐藏弹出窗口
        volumeButton.setOnMouseClicked(event -> {
            if (popup.isShowing()) {
                popup.hide();
            } else {
                popup.show(volumeButton, 
                    volumeButton.localToScreen(volumeButton.getBoundsInLocal()).getMinX() - 45, 
                    volumeButton.localToScreen(volumeButton.getBoundsInLocal()).getMinY() - 80);
            }
        });

        // 将所有控件添加到主容器
        playerBar.getChildren().addAll(songInfoBox, controlBox, progressBox, volumeButton);

        // 设置播放器状态监听
        // 监听播放器状态变化
        player.addPlayerStatusListener(mediaPlayer -> {
            if (mediaPlayer != null) {
                // 设置播放状态图标
                mediaPlayer.statusProperty().addListener((obs, oldStatus, newStatus) -> {
                    if (newStatus == MediaPlayer.Status.PLAYING) {
                        playPauseIcon.setImage(new Image("static/play-icon.png", 24, 24, true, true));
                    } else if (newStatus == MediaPlayer.Status.PAUSED || newStatus == MediaPlayer.Status.STOPPED) {
                        playPauseIcon.setImage(new Image("static/pause-icon.png", 24, 24, true, true));
                    }
                });

                // 监听当前播放时间变化
                mediaPlayer.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
                    if (newTime != null && mediaPlayer.getMedia() != null) {
                        Duration totalDuration = mediaPlayer.getMedia().getDuration();
                        if (totalDuration != null && !totalDuration.isUnknown() && totalDuration.greaterThan(Duration.ZERO)) {
                            // 更新当前时间标签
                            int seconds = (int) newTime.toSeconds();
                            currentTimeLabel.setText(formatDuration(seconds));

                            // 更新总时长标签
                            int totalSeconds = (int) totalDuration.toSeconds();
                            totalTimeLabel.setText(formatDuration(totalSeconds));

                            // 更新进度条（不触发拖动事件）
                            if (!progressSlider.isValueChanging()) {
                                double progress = seconds * 100.0 / totalSeconds;
                                progressSlider.setValue(progress);
                            }
                        }
                    }
                });

                // 当媒体准备好时更新总时长
                mediaPlayer.setOnReady(() -> {
                    Duration totalDuration = mediaPlayer.getMedia().getDuration();
                    if (totalDuration != null && !totalDuration.isUnknown()) {
                        totalTimeLabel.setText(formatDuration((int) totalDuration.toSeconds()));
                    }
                });
            }
        });

        return playerBar;
    }

    // 格式化时间为 mm:ss
    private String formatDuration(int seconds) {
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d", minutes, remainingSeconds);
    }

    // 更新当前歌曲信息（封面、标题、歌手）
    private void updateCurrentSongInfo(SongsResp song) {
        if (song != null) {
            // 更新封面
            updateCurrentSongImageView(song);

            // 更新歌曲标题和歌手
            VBox songDetails = (VBox) ((HBox) playerBar.getChildren().get(0)).getChildren().get(1);
            Label titleLabel = (Label) songDetails.getChildren().get(0);
            Label artistLabel = (Label) songDetails.getChildren().get(1);

            titleLabel.setText(song.getTitle());
            artistLabel.setText(song.getArtist());
        
        // 更新喜欢按钮状态
        HBox songInfoBox = (HBox) playerBar.getChildren().get(0);
        Button likeButton = (Button) songInfoBox.getChildren().get(2);
        ImageView likeIcon;
        
        if (song.getIsLiked() != null && song.getIsLiked()) {
            likeIcon = new ImageView(new Image("static/heart-filled.png", 20, 20, true, true));
        } else {
            likeIcon = new ImageView(new Image("static/heart-icon.png", 20, 20, true, true));
        }
        
        likeButton.setGraphic(likeIcon);

            // 如果正在显示歌词页面，更新歌词
            if (isShowingLyrics) {
                updateLyricsView(song);
            }
            
            // 更新播放列表（如果当前歌曲不在播放列表中）
            String filePath = song.getFilePath();
            List<String> currentPlaylist = player.getPlaylist();
            if (!currentPlaylist.contains(filePath)) {
                // 获取所有歌曲的文件路径
                List<String> allSongPaths = new ArrayList<>();
                try {
                    Result<List<SongsResp>> result = songsController.queryAll();
                    if (result.isSuccess() && result.getData() != null) {
                        for (SongsResp songItem : result.getData()) {
                            allSongPaths.add(songItem.getFilePath());
                        }
                        // 设置播放列表
                        player.setPlaylist(allSongPaths);
                        log.info("已更新播放列表，共{}首歌曲", allSongPaths.size());
                    }
                } catch (Exception e) {
                    log.error("获取所有歌曲失败", e);
                }
            }
        }
    }

    private void updateCurrentSongImageView(SongsResp song) {
        if (song != null && song.getPicture() != null) {
            currentSongImageView.setImage(new Image(song.getPicture()));
        } else {
            // 设置默认图片
            currentSongImageView.setImage(new Image("static/default-cover.png"));
        }
    }

    private VBox createLeftPanel() {
        leftPanel = new VBox(15); // 增加整体间距
        leftPanel.setPadding(new Insets(15));
        leftPanel.setStyle("-fx-background-color: #f8f8f8;");
        leftPanel.setPrefWidth(220); // 设置固定宽度
        leftPanel.setMinWidth(200);

        // 添加顶部用户信息
        leftPanel.getChildren().add(createUserInfo());

        // 添加分隔符和标题
        HBox titleBox = new HBox();
        titleBox.setPadding(new Insets(10, 5, 5, 5));
        Label musicTitle = new Label("音乐馆");
        musicTitle.setStyle("-fx-font-weight: bold; -fx-font-size: 16px;");
        titleBox.getChildren().add(musicTitle);
        
        // 添加分隔线
        Separator separator = new Separator();
        separator.setStyle("-fx-opacity: 0.3;");
        
        leftPanel.getChildren().addAll(separator, titleBox);

        // 添加中间功能列表
        leftPanel.getChildren().add(createFunctionList());

        // 添加"我的音乐"标题
        HBox myMusicTitleBox = new HBox();
        myMusicTitleBox.setPadding(new Insets(15, 5, 5, 5));
        Label myMusicTitle = new Label("我的音乐");
        myMusicTitle.setStyle("-fx-font-weight: bold; -fx-font-size: 16px;");
        myMusicTitleBox.getChildren().add(myMusicTitle);
        
        // 添加另一条分隔线
        Separator separator2 = new Separator();
        separator2.setStyle("-fx-opacity: 0.3;");
        
        leftPanel.getChildren().addAll(separator2, myMusicTitleBox);

        // 添加底部自建歌单和收藏歌单
        leftPanel.getChildren().add(createBottomPlaylists());

        return leftPanel;
    }

    private HBox createUserInfo() {
        HBox userInfoBox = new HBox(10);
        userInfoBox.setPadding(new Insets(10));
        userInfoBox.setAlignment(Pos.CENTER_LEFT);
        
        // 获取当前用户信息
        Result<UsersResp> currentUserInfo = usersController.getCurrentUserInfo();
        String userName = "logos";
        String avatarPath = "static/default-avatar.png";
        
        if (currentUserInfo.isSuccess() && currentUserInfo.getData() != null) {
            UsersResp currentUser = currentUserInfo.getData();
            userName = currentUser.getUsername();
            // 如果有头像，则使用用户头像
            if (currentUser.getAvatar() != null && !currentUser.getAvatar().isEmpty()) {
                avatarPath = currentUser.getAvatar();
            }
        }

        // 用户头像（添加圆形效果）
        ImageView userAvatar = new ImageView(new Image(avatarPath));
        userAvatar.setFitWidth(40);
        userAvatar.setFitHeight(40);
        
        // 创建圆形裁剪
        Circle clip = new Circle(20, 20, 20);
        userAvatar.setClip(clip);
        
        // 添加头像边框效果
        StackPane avatarContainer = new StackPane();
        Circle border = new Circle(20, 20, 21);
        border.setFill(Color.TRANSPARENT);
        border.setStroke(Color.web("#1db954"));
        border.setStrokeWidth(2);
        avatarContainer.getChildren().addAll(userAvatar, border);
        
        // VBox存放用户名和操作选项
        VBox userInfoVBox = new VBox(3);
        
        // 用户名标签
        Label userName1 = new Label(userName);
        userName1.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
        
        // 切换账号链接
        Hyperlink switchAccountLink = new Hyperlink("切换账号");
        switchAccountLink.setStyle("-fx-font-size: 12px; -fx-text-fill: #1db954;");
        
        // 切换账号事件
        switchAccountLink.setOnAction(event -> {
            // 弹窗确认是否切换账号
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("切换账号");
            alert.setHeaderText(null);
            alert.setContentText("确定要退出当前账号吗？");
            
            Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent() && result.get() == ButtonType.OK) {
                // 清除缓存
                redisUtil.del(RedisConstant.SONG_LIKED_USER+LocalSessionStorageUtil.getLoginSession()[0]);
                redisUtil.del(RedisConstant.ALL_SONG);
                // 清除登录态
                redisUtil.del(RedisConstant.USER_LOGIN_SESSION + LocalSessionStorageUtil.getLoginSession()[0]);
                LocalSessionStorageUtil.clearLoginSession();
                
                // 打开登录界面
                LoginFxUi loginFxUi = SpringContextUtil.getBean(LoginFxUi.class);
                Stage loginStage = new Stage();
                try {
                    loginFxUi.start(loginStage);
                    
                    // 关闭当前主窗口（获取当前舞台）
                    Stage currentStage = (Stage) switchAccountLink.getScene().getWindow();
                    currentStage.close();
                } catch (Exception ex) {
                    log.error("打开登录界面失败", ex);
                }
            }
        });
        
        userInfoVBox.getChildren().addAll(userName1, switchAccountLink);
        
        // 将头像容器和用户信息添加到 HBox
        userInfoBox.getChildren().addAll(avatarContainer, userInfoVBox);
        
        // 设置美化效果
        userInfoBox.setStyle("-fx-background-color: #f5f5f7; -fx-background-radius: 10px;");
        
        // 添加鼠标悬停效果
        userInfoBox.setOnMouseEntered(e -> 
            userInfoBox.setStyle("-fx-background-color: #e8e8e8; -fx-background-radius: 10px;"));
        
        userInfoBox.setOnMouseExited(e -> 
            userInfoBox.setStyle("-fx-background-color: #f5f5f7; -fx-background-radius: 10px;"));

        return userInfoBox;
    }


    private HBox createTopSearchBar() {
        HBox topBar = new HBox(10);
        topBar.setPadding(new Insets(10));
        topBar.setAlignment(Pos.CENTER_LEFT);
        topBar.setStyle("-fx-background-color: #f5f5f7;");

        // 搜索框
        HBox searchBox = new HBox();
        searchBox.setStyle("-fx-background-color: #e6e6e6; -fx-background-radius: 15px;");
        searchBox.setPadding(new Insets(5, 10, 5, 10));
        searchBox.setAlignment(Pos.CENTER_LEFT);

        // 搜索图标
        ImageView searchIcon = new ImageView(new Image("static/search-icon.png", 16, 16, true, true));

        // 搜索输入框
        TextField searchField = new TextField();
        searchField.setPromptText("搜索音乐");
        searchField.setPrefWidth(250);
        searchField.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");

        searchBox.getChildren().addAll(searchIcon, searchField);
        HBox.setHgrow(searchBox, Priority.ALWAYS);

        topBar.getChildren().addAll(searchBox);
        return topBar;
    }


    private ListView<String> createFunctionList() {
        ListView<String> functionList = new ListView<>();
        functionList.getStyleClass().add("custom-list-view");
        functionList.setStyle("-fx-background-color: #f5f5f7; -fx-background-radius: 10px; -fx-border-radius: 10px;");
        
        // 设置列表项
        ObservableList<String> items = FXCollections.observableArrayList(
                "主页",
                "个人中心",
                "喜欢",
                "最近播放",
                "发现歌单",
                "AI聊天"
        );
        functionList.setItems(items);

        // 自定义单元格渲染
        functionList.setCellFactory(param -> new ListCell<>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    // 创建包含图标和文本的水平布局
                    HBox cellBox = new HBox(10);
                    cellBox.setAlignment(Pos.CENTER_LEFT);
                    cellBox.setPadding(new Insets(8, 10, 8, 10));
                    
                    // 创建并设置图标
                    ImageView iconView = new ImageView();
                    iconView.setFitWidth(22);
                    iconView.setFitHeight(22);
                    
                    // 根据项目设置不同的图标
                    switch (item) {
                        case "主页":
                            iconView.setImage(new Image("static/home.png"));
                            break;
                        case "个人中心":
                            iconView.setImage(new Image("static/user-icon.png"));
                            break;
                        case "喜欢":
                            iconView.setImage(new Image("static/heart-icon.png"));
                            break;
                        case "最近播放":
                            iconView.setImage(new Image("static/history-play.png"));
                            break;
                        case "发现歌单":
                            iconView.setImage(new Image("static/playlist-icon.png"));
                            break;
                        case "AI聊天":
                            iconView.setImage(new Image("static/chat-icon.png"));
                            break;
                        default:
                            iconView.setImage(null);
                    }
                    
                    // 文本标签
                    Label textLabel = new Label(item);
                    textLabel.setStyle("-fx-font-size: 14px;");
                    
                    // 将图标和文本添加到布局中
                    cellBox.getChildren().addAll(iconView, textLabel);
                    
                    // 设置选中项的样式
                    if (isSelected()) {
                        cellBox.setStyle("-fx-background-color: #ddefff; -fx-background-radius: 6px;");
                        textLabel.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #1db954;");
                        iconView.setOpacity(1.0);
                    } else {
                        cellBox.setStyle("-fx-background-color: transparent;");
                        textLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #333333;");
                        iconView.setOpacity(0.7);
                    }
                    
                    // 设置图形而不是文本
                    setGraphic(cellBox);
                    setText(null);
                    
                    // 添加鼠标悬停效果
                    cellBox.setOnMouseEntered(e -> {
                        if (!isSelected()) {
                            cellBox.setStyle("-fx-background-color: #f0f0f0; -fx-background-radius: 6px;");
                            iconView.setOpacity(0.9);
                        }
                    });
                    
                    cellBox.setOnMouseExited(e -> {
                        if (!isSelected()) {
                            cellBox.setStyle("-fx-background-color: transparent;");
                            iconView.setOpacity(0.7);
                        }
                    });
                }
            }
        });

        // 设置默认选中第一项
        functionList.getSelectionModel().select(0);

        // 添加选择监听器
        functionList.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal != null) {
                switch (newVal) {
                    case "主页":
                        showHomePage();
                        break;
                    case "个人中心":
                        showPersonalCenter();
                        break;
                    case "喜欢":
                        showLikes();
                        break;
                    case "最近播放":
                        showRecentPlays();
                        break;
                    case "发现歌单":
                        showAllPlaylistsPage();
                        break;
                    case "AI聊天":
                        showAiChatPage();
                        break;
                }
            }
        });
        
        // 设置列表不显示焦点边框
        functionList.setFocusTraversable(false);
        
        return functionList;
    }

    private void showHomePage() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();
            
            // 创建一个内容容器，用于放置所有主页内容
            VBox contentBox = new VBox(20);
            contentBox.setPadding(new Insets(10));
            
            // 1. 欢迎区域
            HBox welcomeBox = new HBox(15);
            welcomeBox.setAlignment(Pos.CENTER_LEFT);
            welcomeBox.setPadding(new Insets(10, 0, 20, 0));
            
            Result<UsersResp> currentUserInfo = usersController.getCurrentUserInfo();
            String userName = "logos";
            if (currentUserInfo.isSuccess()) {
                UsersResp currentUser = currentUserInfo.getData();
                userName = currentUser.getUsername();
            }
            Label greetingLabel = new Label("Hi " + userName + " 今日为你推荐");
            greetingLabel.setStyle("-fx-font-size: 22px; -fx-font-weight: bold;");

            welcomeBox.getChildren().addAll(greetingLabel);
            
            // 2. 今日推荐歌曲
            Label todaySongsLabel = new Label("今日推荐歌曲");
            todaySongsLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-padding: 10 0 10 0;");
            
            // 创建今日推荐歌曲列表
            daySongsGrid = createTodaySongsGrid();
            
            // 在显示主页时，立即刷新一次
            refreshDaySongsGrid();
            
            // 3. 横向滚动推荐区域
            HBox recommendHeaderBox = new HBox(15);
            recommendHeaderBox.setAlignment(Pos.CENTER_LEFT);
            
            Label recommendLabel = new Label("推荐歌单");
            recommendLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-padding: 15 0 10 0;");
            
            Button refreshButton = new Button("换一批");
            refreshButton.setStyle("-fx-background-color: transparent; -fx-text-fill: #1db954; -fx-border-color: #1db954; -fx-border-radius: 15; -fx-padding: 5 15;");
            refreshButton.setCursor(Cursor.HAND);
            
            // 添加刷新按钮事件
            refreshButton.setOnAction(e -> {
                // 删除缓存再重新获取
                redisUtil.del(RedisConstant.PLAYLIST_RECOMMEND+LocalSessionStorageUtil.getLoginSession()[0]);
                // 重新获取推荐歌单
                refreshRecommendPlaylists();
            });
            
            recommendHeaderBox.getChildren().addAll(recommendLabel, refreshButton);
            
            // 使用ScrollPane创建水平滚动区域
            StackPane horizontalScroller = createHorizontalScroller();
            
            // 4. 专题推荐区域 (Daily 30/社区专区等)
            Label featuredLabel = new Label("热门推荐");
            featuredLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-padding: 10 0 10 0;");
            
            // 使用GridPane显示专题区域
            GridPane featuredGrid = createFeaturedGrid();
            
            // 5. 推荐歌曲列表
            Label recommendedSongsLabel = new Label("推荐歌曲");
            recommendedSongsLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-padding: 15 0 10 0;");
            
            // 创建推荐歌曲列表
            VBox recommendedSongsBox = createRecommendedSongsList();

            // 添加所有内容到内容容器
            contentBox.getChildren().addAll(
                    welcomeBox,
                    todaySongsLabel,
                    daySongsGrid,
                    recommendHeaderBox,
                    horizontalScroller,
                    featuredLabel,
                    featuredGrid,
                    recommendedSongsLabel,
                    recommendedSongsBox
            );
            
            // 创建滚动面板，将内容容器放入其中
            ScrollPane scrollPane = new ScrollPane(contentBox);
            scrollPane.setFitToWidth(true);
            scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
            scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
            scrollPane.getStyleClass().add("edge-to-edge");
            scrollPane.setStyle("-fx-background-color: transparent;");
            
            // 添加滚动面板到右侧面板
            rightPanel.getChildren().add(scrollPane);
            VBox.setVgrow(scrollPane, Priority.ALWAYS);
        }
    }
    
    private GridPane createTodaySongsGrid() {
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);
        
        // 添加表头
        Label numberLabel = new Label("#");
        numberLabel.setStyle("-fx-font-weight: bold;");
        grid.add(numberLabel, 0, 0);
        
        Label titleLabel = new Label("歌曲");
        titleLabel.setStyle("-fx-font-weight: bold;");
        grid.add(titleLabel, 1, 0);
        
        Label artistLabel = new Label("歌手");
        artistLabel.setStyle("-fx-font-weight: bold;");
        grid.add(artistLabel, 2, 0);
        
        Label durationLabel = new Label("时长");
        durationLabel.setStyle("-fx-font-weight: bold;");
        grid.add(durationLabel, 3, 0);
        
        // 添加好句表头
        Label keyLrcLabel = new Label("好句");
        keyLrcLabel.setStyle("-fx-font-weight: bold;");
        grid.add(keyLrcLabel, 4, 0);
        
        // 添加喜欢表头
        Label likeLabel = new Label("喜欢");
        likeLabel.setStyle("-fx-font-weight: bold;");
        grid.add(likeLabel, 5, 0);
        GridPane.setHalignment(likeLabel, javafx.geometry.HPos.CENTER);
        
        // 添加到歌单表头
        Label addToPlaylistLabel = new Label("添加");
        addToPlaylistLabel.setStyle("-fx-font-weight: bold;");
        grid.add(addToPlaylistLabel, 6, 0);
        GridPane.setHalignment(addToPlaylistLabel, javafx.geometry.HPos.CENTER);
        
        // 使用最新获取的每日推荐歌曲
        if (currentDaySongs.isEmpty()) {
            // 如果还没有获取到数据，尝试再次获取
            updateDaySongs();
        }
        
        // 创建和添加歌曲行
        for (int i = 0; i < currentDaySongs.size(); i++) {
            addSongRowToGrid(grid, currentDaySongs.get(i), i);
        }
        
        // 设置列宽
        ColumnConstraints col1 = new ColumnConstraints(30);  // 序号列
        ColumnConstraints col2 = new ColumnConstraints(240); // 歌曲列
        ColumnConstraints col3 = new ColumnConstraints(140); // 歌手列
        ColumnConstraints col4 = new ColumnConstraints(50);  // 时长列
        ColumnConstraints col5 = new ColumnConstraints(180); // 好句列
        ColumnConstraints col6 = new ColumnConstraints(50);  // 喜欢列
        ColumnConstraints col7 = new ColumnConstraints(50);  // 添加到歌单列
        grid.getColumnConstraints().addAll(col1, col2, col3, col4, col5, col6, col7);
        
        return grid;
    }
    
    // 添加单行歌曲到网格
    private void addSongRowToGrid(GridPane grid, SongsResp song, int index) {
        // 行背景 - 用于悬停效果
        HBox rowBackground = new HBox();
        rowBackground.setPrefHeight(50);
        rowBackground.setPrefWidth(500);
        GridPane.setColumnSpan(rowBackground, 7); // 扩展行背景跨度到7列，包括喜欢按钮和添加到歌单按钮列
        grid.add(rowBackground, 0, index + 1);
        
        // 序号
        Label number = new Label(String.valueOf(index + 1));
        number.setStyle("-fx-text-fill: #808080;");
        grid.add(number, 0, index + 1);
        
        // 歌曲（带封面）
        HBox songBox = new HBox(10);
        songBox.setAlignment(Pos.CENTER_LEFT);
        
        ImageView cover = new ImageView(new Image(song.getPicture(), 40, 40, true, true));
        
        VBox songInfo = new VBox(3);
        Label songTitle = new Label(song.getTitle());
        songTitle.setStyle("-fx-font-weight: bold;");
        songInfo.getChildren().add(songTitle);
        
        songBox.getChildren().addAll(cover, songInfo);
        grid.add(songBox, 1, index + 1);
        
        // 歌手
        Label artist = new Label(song.getArtist());
        artist.setStyle("-fx-text-fill: #404040;");
        grid.add(artist, 2, index + 1);
        
        // 时长
        Label duration = new Label(formatDuration(song.getDuration()));
        duration.setStyle("-fx-text-fill: #808080;");
        grid.add(duration, 3, index + 1);
        
        // 好句
        Label keyLrc = new Label(song.getKeyLrc() != null ?  song.getKeyLrc()  : "");
        keyLrc.setStyle("-fx-text-fill: #808080; -fx-font-style: italic;");
        keyLrc.setWrapText(true);
        grid.add(keyLrc, 4, index + 1);
        
        // 喜欢按钮
        Button likeButton = new Button();
        likeButton.getStyleClass().add("like-button");
        likeButton.setStyle("-fx-background-color: transparent;");
        
        // 根据歌曲的isLiked属性设置按钮状态
        updateLikeButtonAppearance(likeButton, song.getIsLiked() != null && song.getIsLiked());
        
        // 添加点击事件
        likeButton.setOnAction(e -> {
            toggleLikeSong(likeButton, song);
        });
        
        // 添加到网格
        grid.add(likeButton, 5, index + 1);
        GridPane.setHalignment(likeButton, javafx.geometry.HPos.CENTER);
        
        // 添加到歌单按钮
        Button addToPlaylistButton = new Button();
        addToPlaylistButton.setStyle("-fx-background-color: transparent;");
        ImageView addIcon = new ImageView(new Image("static/add-to-playlist.png", 20, 20, true, true));
        addToPlaylistButton.setGraphic(addIcon);
        addToPlaylistButton.setTooltip(new Tooltip("添加到歌单"));
        
        // 添加点击事件
        addToPlaylistButton.setOnAction(e -> {
            showAddToPlaylistDialog(song);
        });
        
        // 添加到网格
        grid.add(addToPlaylistButton, 6, index + 1);
        GridPane.setHalignment(addToPlaylistButton, javafx.geometry.HPos.CENTER);
        
        // 添加鼠标悬停效果和点击事件
        rowBackground.setOnMouseEntered(e -> {
            rowBackground.setStyle("-fx-background-color: rgba(0,0,0,0.05);");
        });
        rowBackground.setOnMouseExited(e -> {
            rowBackground.setStyle("-fx-background-color: transparent;");
        });
        rowBackground.setOnMouseClicked(event -> {
            // 设置当前播放歌曲
            currentSong = song;
            updateCurrentSongInfo(currentSong);
            if (event.getClickCount() == 2) {
                log.info("播放歌曲: " + currentSong.getTitle());
                
                // 实际播放歌曲逻辑
                player.play(currentSong.getFilePath());
            }
        });
    }

    private StackPane createHorizontalScroller() {
        // 创建水平布局容器
        HBox content = new HBox(15);
        content.setPadding(new Insets(10));

        // 显示加载指示器
        ProgressIndicator loadingIndicator = new ProgressIndicator();
        loadingIndicator.setMaxSize(40, 40);
        VBox loadingBox = new VBox(loadingIndicator);
        loadingBox.setAlignment(Pos.CENTER);
        loadingBox.setPrefWidth(150);
        content.getChildren().add(loadingBox);

        // 异步加载推荐歌单
        new Thread(() -> {
            try {
                Result<List<PlaylistResp>> result = playlistController.getRecommendPlaylist();
                
                Platform.runLater(() -> {
                    // 移除加载指示器
                    content.getChildren().clear();
                    
                    if (result.isSuccess() && result.getData() != null && !result.getData().isEmpty()) {
                        List<PlaylistResp> recommendPlaylists = result.getData();
                        
                        // 创建并添加推荐歌单卡片
                        for (PlaylistResp playlist : recommendPlaylists) {
                            VBox card = createRecommendationCardFromPlaylist(playlist);
                            content.getChildren().add(card);
                        }
                    } else {
                        // 加载失败或无数据时使用默认推荐
                        String[][] defaultItems = {
            {"放松吧", "参差荣枯丨声乐弹拨两相宜～", "static/logo.jpg"},
            {"流行热歌", "当下热门流行歌曲精选", "static/logo.jpg"},
            {"华语经典", "永不过时的华语经典歌曲", "static/logo.jpg"},
            {"轻音乐", "舒缓压力的轻音乐集锦", "static/logo.jpg"},
                            {"摇滚专区", "热血沸腾的摇滚金曲", "static/logo.jpg"}
                        };

                        // 创建并添加默认推荐卡片
                        for (String[] item : defaultItems) {
            VBox card = createRecommendationCard(item[0], item[1], item[2]);
            content.getChildren().add(card);
        }
                    }
                });
            } catch (Exception e) {
                log.error("加载推荐歌单失败", e);
                
                // 加载失败时使用默认推荐
                Platform.runLater(() -> {
                    content.getChildren().clear();
                    
                    String[][] defaultItems = {
                        {"放松吧", "参差荣枯丨声乐弹拨两相宜～", "static/logo.jpg"},
                        {"流行热歌", "当下热门流行歌曲精选", "static/logo.jpg"},
                        {"华语经典", "永不过时的华语经典歌曲", "static/logo.jpg"},
                        {"轻音乐", "舒缓压力的轻音乐集锦", "static/logo.jpg"},
                        {"摇滚专区", "热血沸腾的摇滚金曲", "static/logo.jpg"}
                    };

                    // 创建并添加默认推荐卡片
                    for (String[] item : defaultItems) {
                        VBox card = createRecommendationCard(item[0], item[1], item[2]);
                        content.getChildren().add(card);
                    }
                });
            }
        }).start();

        // 创建滚动窗格
        ScrollPane scrollPane = new ScrollPane(content);
        scrollPane.setFitToHeight(true);
        scrollPane.setPrefHeight(200);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);  // 隐藏水平滚动条
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);  // 隐藏垂直滚动条
        scrollPane.getStyleClass().add("edge-to-edge");
        scrollPane.setStyle("-fx-background-color: transparent;");

        // 改进滚动效果：使用鼠标滚轮和拖动都可以水平滚动
        content.setOnScroll(event -> {
            double deltaY = event.getDeltaY();
            double width = scrollPane.getContent().getBoundsInLocal().getWidth();
            double hvalue = scrollPane.getHvalue();
            // 调整滚动速度和方向
            double newHvalue = hvalue - (deltaY / width) * 5;
            // 确保值在0-1之间
            newHvalue = Math.min(Math.max(newHvalue, 0), 1);
            scrollPane.setHvalue(newHvalue);
            event.consume(); // 防止事件继续传播
        });

        // 添加左右滚动按钮
        StackPane scrollerContainer = new StackPane();
        scrollerContainer.getChildren().add(scrollPane);
        
        // 左滚动按钮
        Button leftButton = new Button("<");
        leftButton.getStyleClass().add("scroll-button");
        leftButton.setStyle("-fx-background-color: rgba(0,0,0,0.3); -fx-text-fill: white; -fx-font-weight: bold;");
        leftButton.setOnAction(e -> {
            double newValue = scrollPane.getHvalue() - 0.2; // 每次滚动20%
            scrollPane.setHvalue(Math.max(0, newValue));
        });
        
        // 右滚动按钮
        Button rightButton = new Button(">");
        rightButton.getStyleClass().add("scroll-button");
        rightButton.setStyle("-fx-background-color: rgba(0,0,0,0.3); -fx-text-fill: white; -fx-font-weight: bold;");
        rightButton.setOnAction(e -> {
            double newValue = scrollPane.getHvalue() + 0.2; // 每次滚动20%
            scrollPane.setHvalue(Math.min(1, newValue));
        });
        
        // 设置按钮位置
        StackPane.setAlignment(leftButton, Pos.CENTER_LEFT);
        StackPane.setAlignment(rightButton, Pos.CENTER_RIGHT);
        StackPane.setMargin(leftButton, new Insets(0, 0, 0, 5));
        StackPane.setMargin(rightButton, new Insets(0, 5, 0, 0));
        
        // 仅当鼠标悬停在区域上时显示按钮
        leftButton.setOpacity(0);
        rightButton.setOpacity(0);
        
        scrollerContainer.setOnMouseEntered(e -> {
            leftButton.setOpacity(0.8);
            rightButton.setOpacity(0.8);
        });
        
        scrollerContainer.setOnMouseExited(e -> {
            leftButton.setOpacity(0);
            rightButton.setOpacity(0);
        });
        
        // 添加按钮到容器
        scrollerContainer.getChildren().addAll(leftButton, rightButton);
        
        return scrollerContainer;
    }

    private VBox createRecommendationCard(String title, String description, String imagePath) {
        VBox card = new VBox(5);
        card.setPrefWidth(150);
        card.setCursor(Cursor.HAND);

        // 卡片图片
        ImageView imageView = new ImageView(new Image(imagePath, 150, 150, true, true));

        // 圆角效果 (在实际JavaFX中通过CSS实现)
        imageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 0);");

        // 卡片标题和描述
        Label titleLabel = new Label(title);
        titleLabel.setStyle("-fx-font-weight: bold;");
        titleLabel.setWrapText(true);
        titleLabel.setPrefWidth(150);

        Label descLabel = new Label(description);
        descLabel.setStyle("-fx-text-fill: #808080; -fx-font-size: 12px;");
        descLabel.setWrapText(true);
        descLabel.setPrefWidth(150);

        card.getChildren().addAll(imageView, titleLabel, descLabel);

        // 添加点击事件
        card.setOnMouseClicked(event -> {
            // TODO: 实现点击播放列表的逻辑
            System.out.println("选择了播放列表: " + title);
        });

        return card;
    }

    private GridPane createFeaturedGrid() {
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);

        // 定义专题项目
        String[][] featuredItems = {
                {"四季-陈奕迅", "每日30首", "static/logo.jpg"},
                {"还是分开-张叶蕾", "官选模式", "static/logo.jpg"},
                {"社区专区", "", "static/logo.jpg"},
                {"失重少年", "太空感舒适音乐", "static/logo.jpg"}
        };

        // 创建并添加专题卡片
        int column = 0;
        for (String[] item : featuredItems) {
            StackPane card = createFeaturedCard(item[0], item[1], item[2]);
            grid.add(card, column % 4, column / 4);
            column++;
        }

        return grid;
    }

    private StackPane createFeaturedCard(String title, String subTitle, String imagePath) {
        StackPane card = new StackPane();
        card.setPrefSize(280, 120);
        card.setCursor(Cursor.HAND);

        // 背景图片
        ImageView backgroundImage = new ImageView(new Image(imagePath, 280, 120, true, true));

        // 半透明黑色渐变遮罩
        Rectangle overlay = new Rectangle(280, 120);
        overlay.setFill(Color.rgb(0, 0, 0, 0.3));

        // 文字容器
        VBox textBox = new VBox(5);
        textBox.setPadding(new Insets(15));
        textBox.setAlignment(Pos.BOTTOM_LEFT);

        // 标题和副标题
        Label titleLabel = new Label(title);
        titleLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: white;");

        Label subTitleLabel = new Label(subTitle);
        subTitleLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #cccccc;");

        textBox.getChildren().addAll(titleLabel);
        if (!subTitle.isEmpty()) {
            textBox.getChildren().add(subTitleLabel);
        }

        // 组装卡片
        card.getChildren().addAll(backgroundImage, overlay, textBox);

        // 添加点击事件
        card.setOnMouseClicked(event -> {
            // TODO: 实现点击专题的逻辑
            System.out.println("选择了专题: " + title);
        });

        return card;
    }

    private GridPane createPlaylistsGrid() {
        GridPane grid = new GridPane();
        grid.setHgap(15);
        grid.setVgap(15);

        // 定义歌单数据
        String[][] playlists = {
                {"[陈奕迅]讲故事的人总是很难熬", "901.1万", "static/logo.jpg"},
                {"抖音热歌 | 火爆全网的旋律", "5331.4万", "static/logo.jpg"},
                {"[香港] 致敬黄霑，不变经典", "495.6万", "static/logo.jpg"},
                {"《云顶之弈》强音会原声带", "5.8万", "static/logo.jpg"},
                {"杨坤坐谈：在歌喉里感受苦涩人生", "1.1亿", "static/logo.jpg"},
                {"午后时光：沉浸在舒缓的吉他旋律中", "235.6万", "static/logo.jpg"}
        };

        // 创建并添加歌单卡片
        int column = 0;
        for (String[] playlist : playlists) {
            VBox card = createPlaylistCard(playlist[0], playlist[1], playlist[2]);
            grid.add(card, column % 5, column / 5);
            column++;
        }

        return grid;
    }

    private VBox createPlaylistCard(String title, String playCount, String imagePath) {
        VBox card = new VBox(5);
        card.setPrefWidth(180);
        card.setCursor(Cursor.HAND);

        // 创建歌单封面的StackPane（包含图片和播放量）
        StackPane coverPane = new StackPane();

        // 歌单封面图片
        ImageView coverImage = new ImageView(new Image(imagePath, 180, 180, true, true));

        // 播放量标签容器
        HBox playCountBox = new HBox(5);
        playCountBox.setPadding(new Insets(5));
        playCountBox.setAlignment(Pos.TOP_RIGHT);
        playCountBox.setMaxWidth(Double.MAX_VALUE);

        // 播放图标
        ImageView playIcon = new ImageView(new Image("static/logo.png", 12, 12, true, true));

        // 播放量文本
        Label playCountLabel = new Label(playCount);
        playCountLabel.setStyle("-fx-text-fill: white; -fx-font-size: 12px;");

        playCountBox.getChildren().addAll(playIcon, playCountLabel);

        // 组装封面
        coverPane.getChildren().addAll(coverImage, playCountBox);
        StackPane.setAlignment(playCountBox, Pos.TOP_RIGHT);

        // 歌单标题
        Label titleLabel = new Label(title);
        titleLabel.setWrapText(true);
        titleLabel.setPrefWidth(180);

        // 组装卡片
        card.getChildren().addAll(coverPane, titleLabel);

        // 添加点击事件
        card.setOnMouseClicked(event -> {
            // TODO: 实现点击歌单的逻辑
            System.out.println("选择了歌单: " + title);
        });

        return card;
    }

    private VBox createRightPanel() {
        rightPanel = new VBox();
        rightPanel.setSpacing(10);
        rightPanel.setPadding(new Insets(10));
        return rightPanel;
    }

    private void showSongs() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();

            Label label = new Label("歌曲列表");
            ListView<String> songList = new ListView<>();
            songList.getItems().addAll("歌曲1", "歌曲2", "歌曲3");

            rightPanel.getChildren().addAll(label, songList);
        }
    }

    private void showLikes() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();

            // 使用LikesPageUi类创建喜欢页面
            LikesPageUi likesPageUi = new LikesPageUi(player, song -> {
                // 当选择歌曲时更新当前歌曲信息
                currentSong = song;
                    updateCurrentSongInfo(currentSong);
            });
            
            // 获取喜欢页面并添加到右侧面板
            VBox likesPage = likesPageUi.createLikesPage();
            rightPanel.getChildren().add(likesPage);
            VBox.setVgrow(likesPage, Priority.ALWAYS);
        }
    }
    


    private void showRecentPlays() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();
            
            // 使用RecentPlayPageUi类创建最近播放页面
            RecentPlayPageUi recentPlayPageUi = new RecentPlayPageUi(player, song -> {
                // 当选择歌曲时更新当前歌曲信息
                currentSong = song;
                updateCurrentSongInfo(currentSong);
            });
            
            // 获取最近播放页面并添加到右侧面板
            VBox recentPlayPage = recentPlayPageUi.createRecentPlayPage();
            rightPanel.getChildren().add(recentPlayPage);
            VBox.setVgrow(recentPlayPage, Priority.ALWAYS);
        }
    }


    // 切换歌词视图
    private void toggleLyricsView() {
        if (isShowingLyrics) {
            // 返回主内容
            root.setCenter(mainContentView);
            isShowingLyrics = false;
        } else {
            // 显示歌词
            createLyricsView();
            root.setCenter(lyricsView);
            isShowingLyrics = true;
        }
    }

    // 创建歌词视图
    private void createLyricsView() {
        // 使用BorderPane作为主要布局，以便左右分割
        BorderPane lyricsBorderPane = new BorderPane();
        lyricsBorderPane.setStyle("-fx-background-color: linear-gradient(to right, #1a1a1a, #302030);");
        
        // 创建包裹BorderPane的VBox，以便添加底部按钮
        lyricsView = new VBox(20);
        lyricsView.setAlignment(Pos.CENTER);
        lyricsView.setPadding(new Insets(20));
        lyricsView.setStyle("-fx-background-color: linear-gradient(to right, #1a1a1a, #302030);");
        
        // ----------------- 左侧专辑封面和歌曲信息 -----------------
        VBox leftPanel = new VBox(20);
        leftPanel.setAlignment(Pos.CENTER);
        leftPanel.setPadding(new Insets(30, 40, 30, 40));
        leftPanel.setMinWidth(400);
        leftPanel.setPrefWidth(400);

        // 歌曲大封面
        ImageView largeImageView = new ImageView();
        largeImageView.setFitWidth(350);
        largeImageView.setFitHeight(350);
        
        // 设置圆角
        Rectangle imageClip = new Rectangle(350, 350);
        imageClip.setArcWidth(10);
        imageClip.setArcHeight(10);
        largeImageView.setClip(imageClip);
        
        // 添加阴影效果
        StackPane imageContainer = new StackPane(largeImageView);
        imageContainer.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.5), 20, 0, 0, 0);");
        
        // 设置封面图片
        if (currentSong != null && currentSong.getPicture() != null) {
            largeImageView.setImage(new Image(currentSong.getPicture()));
        } else {
            largeImageView.setImage(new Image("static/logo.jpg"));
        }
        
        // 歌曲信息
        VBox songInfoBox = new VBox(10);
        songInfoBox.setAlignment(Pos.CENTER);
        songInfoBox.setPadding(new Insets(20, 0, 0, 0));

        // 歌曲标题
        Label titleLabel = new Label(currentSong != null ? currentSong.getTitle() : "未知歌曲");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-text-fill: white; -fx-font-weight: bold;");

        // 艺术家
        Label artistLabel = new Label(currentSong != null ? currentSong.getArtist() : "未知艺术家");
        artistLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #cccccc;");

        // 添加专辑信息（如果有）
        Label albumLabel = new Label(currentSong != null && currentSong.getAlbum() != null ? currentSong.getAlbum() : "");
        albumLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #999999; -fx-font-style: italic;");
        
        songInfoBox.getChildren().addAll(titleLabel, artistLabel, albumLabel);
        
        // 添加上述组件到左侧面板
        leftPanel.getChildren().addAll(imageContainer, songInfoBox);
        
        // ----------------- 右侧歌词部分 -----------------
        VBox rightPanel = new VBox(15);
        rightPanel.setAlignment(Pos.TOP_CENTER);
        rightPanel.setPadding(new Insets(30, 40, 30, 20));
        
        // 歌词标题
        Label lyricsTitle = new Label("歌词");
        lyricsTitle.setStyle("-fx-font-size: 18px; -fx-text-fill: #ffffff; -fx-font-weight: bold;");

        // 创建歌词滚动面板
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(500);
        scrollPane.setStyle("-fx-background-color: rgba(255,255,255,0.05); " + 
                           "-fx-background: rgba(255,255,255,0.05); " +
                           "-fx-background-radius: 10px; " +
                           "-fx-border-radius: 10px; " +
                           "-fx-border-color: rgba(255,255,255,0.1);");
        VBox.setVgrow(scrollPane, Priority.ALWAYS);

        // 添加歌词内容
        VBox lyricsContent = new VBox(15);
        lyricsContent.setId("lyrics-content"); // 设置ID便于查找
        lyricsContent.setAlignment(Pos.TOP_LEFT);
        lyricsContent.setPadding(new Insets(20));
        lyricsContent.setStyle("-fx-background-color: transparent;");

        updateLyricsContent(lyricsContent);

        scrollPane.setContent(lyricsContent);
        
        // 添加歌词相关内容到右侧面板
        rightPanel.getChildren().addAll(lyricsTitle, scrollPane);
        VBox.setVgrow(rightPanel, Priority.ALWAYS);
        
        // 将左右面板添加到BorderPane
        lyricsBorderPane.setLeft(leftPanel);
        lyricsBorderPane.setCenter(rightPanel);

        // 添加返回按钮
        Button backButton = new Button("返回");
        backButton.setStyle("-fx-background-color: #ff7700; " + 
                          "-fx-text-fill: white; " + 
                          "-fx-font-weight: bold; " + 
                          "-fx-padding: 10 20; " +
                          "-fx-background-radius: 5;");
        backButton.setOnAction(e -> {
            stopLyricUpdateTimer(); // 停止歌词更新定时器
            toggleLyricsView();
        });

        HBox buttonBox = new HBox();
        buttonBox.setAlignment(Pos.CENTER);
        buttonBox.setPadding(new Insets(15, 0, 0, 0));
        buttonBox.getChildren().add(backButton);

        // 将BorderPane和按钮添加到主视图
        lyricsView.getChildren().addAll(lyricsBorderPane, buttonBox);
        VBox.setVgrow(lyricsBorderPane, Priority.ALWAYS);

        // 开始歌词更新定时器
        startLyricUpdateTimer(lyricsContent, scrollPane);
    }

    // 开始歌词更新定时器
    private void startLyricUpdateTimer(VBox lyricsContent, ScrollPane scrollPane) {
        stopLyricUpdateTimer(); // 停止已有的定时器

        // 创建100ms刷新的定时器
        lyricUpdateTimeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
            if (player.getMediaPlayer() != null && player.isPlaying) {
                updateHighlightedLyric(lyricsContent, scrollPane);
            }
        }));
        lyricUpdateTimeline.setCycleCount(Timeline.INDEFINITE);
        lyricUpdateTimeline.play();
    }

    // 停止歌词更新定时器
    private void stopLyricUpdateTimer() {
        if (lyricUpdateTimeline != null) {
            lyricUpdateTimeline.stop();
            lyricUpdateTimeline = null;
        }
    }

    // 更新高亮显示的歌词
    private void updateHighlightedLyric(VBox lyricsContent, ScrollPane scrollPane) {
        if (parsedLyrics.isEmpty() || player.getMediaPlayer() == null) {
            return;
        }

        // 获取当前播放时间(毫秒)
        double currentTimeMs = player.getCurrentTime().toMillis();

        // 找出当前应该高亮的歌词行
        int newHighlightIndex = -1;
        for (int i = 0; i < parsedLyrics.size(); i++) {
            // 如果是最后一行或者当前时间在这一行的时间段内
            if (i == parsedLyrics.size() - 1 ||
                    (currentTimeMs >= parsedLyrics.get(i).getTimeMs() &&
                            currentTimeMs < parsedLyrics.get(i + 1).getTimeMs())) {
                newHighlightIndex = i;
                break;
            }
        }

        // 如果高亮行改变了
        if (newHighlightIndex != currentHighlightIndex && newHighlightIndex >= 0 && newHighlightIndex < lyricsContent.getChildren().size()) {
            // 重置之前高亮的行
            if (currentHighlightIndex >= 0 && currentHighlightIndex < lyricsContent.getChildren().size()) {
                HBox previousContainer = (HBox) lyricsContent.getChildren().get(currentHighlightIndex);
                
                // 获取之前高亮行的歌词文本 (第二个子元素是歌词Label)
                Label previousLine = (Label) previousContainer.getChildren().get(1);
                previousLine.setStyle("-fx-text-fill: #e6e6e6; -fx-font-size: 18px;");
                
                // 重置容器背景
                previousContainer.setStyle("-fx-background-color: transparent; -fx-background-radius: 5px;");
            }

            // 设置新的高亮行
            HBox currentContainer = (HBox) lyricsContent.getChildren().get(newHighlightIndex);
            
            // 获取当前高亮行的歌词文本 (第二个子元素是歌词Label)
            Label currentLine = (Label) currentContainer.getChildren().get(1);
            currentLine.setStyle("-fx-text-fill: #ff7700; -fx-font-size: 20px; -fx-font-weight: bold;");
            
            // 设置容器背景
            currentContainer.setStyle("-fx-background-color: rgba(255, 119, 0, 0.1); -fx-background-radius: 5px;");
            
            currentHighlightIndex = newHighlightIndex;

            // 自动滚动到当前行 - 更加精准的滚动位置计算
            // 计算当前行在整个歌词内容中的相对位置
            double lineHeight = currentContainer.getBoundsInLocal().getHeight();
            double totalHeight = lyricsContent.getBoundsInLocal().getHeight();
            double viewportHeight = scrollPane.getViewportBounds().getHeight();
            
            // 计算滚动位置，使当前行位于滚动区域中间位置
            double linePosition = currentContainer.getBoundsInParent().getMinY();
            double scrollOffset = (linePosition + lineHeight / 2) - (viewportHeight / 2);
            double scrollRatio = scrollOffset / (totalHeight - viewportHeight);
            
            // 确保滚动比例在有效范围内
            scrollRatio = Math.min(Math.max(scrollRatio, 0), 1);
            
            // 平滑滚动
            scrollPane.setVvalue(scrollRatio);
        }
    }

    // 更新歌词内容
    private void updateLyricsContent(VBox lyricsContent) {
        lyricsContent.getChildren().clear();
        currentHighlightIndex = -1;
        parsedLyrics.clear();

        if (currentSong == null) {
            Label noLyrics = new Label("没有可显示的歌词");
            noLyrics.setStyle("-fx-text-fill: #999999; -fx-font-style: italic; -fx-font-size: 16px;");
            lyricsContent.getChildren().add(noLyrics);
            return;
        }

        String lrcUrl = currentSong.getLrc();
        if (lrcUrl == null || lrcUrl.isEmpty()) {
            Label noLyrics = new Label("暂无歌词");
            noLyrics.setStyle("-fx-text-fill: #999999; -fx-font-style: italic; -fx-font-size: 16px;");
            
            // 添加装饰元素
            ImageView musicNoteIcon = new ImageView(new Image("static/logo.png", 30, 30, true, true));
            
            VBox emptyLyricBox = new VBox(20);
            emptyLyricBox.setAlignment(Pos.CENTER);
            emptyLyricBox.setPadding(new Insets(50, 0, 0, 0));
            emptyLyricBox.getChildren().addAll(musicNoteIcon, noLyrics);
            
            lyricsContent.getChildren().add(emptyLyricBox);
            return;
        }

        // 创建加载指示器
        ProgressIndicator loadingIndicator = new ProgressIndicator();
        loadingIndicator.setMaxSize(50, 50);
        loadingIndicator.setStyle("-fx-accent: #ff7700;");
        
        Label loadingLabel = new Label("正在加载歌词...");
        loadingLabel.setStyle("-fx-text-fill: #cccccc; -fx-font-size: 14px;");
        
        VBox loadingBox = new VBox(15);
        loadingBox.setAlignment(Pos.CENTER);
        loadingBox.setPadding(new Insets(80, 0, 0, 0));
        loadingBox.getChildren().addAll(loadingIndicator, loadingLabel);
        
        lyricsContent.getChildren().add(loadingBox);

        // 在后台线程中加载歌词
        new Thread(() -> {
            try {
                // 从URL获取歌词内容
                String lyricsText = fetchLyricsFromUrl(lrcUrl);

                // 解析LRC格式歌词
                parseLrcFormat(lyricsText);

                // 回到JavaFX线程更新UI
                Platform.runLater(() -> {
                    lyricsContent.getChildren().clear();

                    if (parsedLyrics.isEmpty()) {
                        Label noLyrics = new Label("无法解析歌词或歌词为空");
                        noLyrics.setStyle("-fx-text-fill: #999999; -fx-font-style: italic; -fx-font-size: 16px;");
                        
                        ImageView errorIcon = new ImageView(new Image("static/logo.png", 30, 30, true, true));
                        errorIcon.setOpacity(0.5);
                        
                        VBox emptyBox = new VBox(20);
                        emptyBox.setAlignment(Pos.CENTER);
                        emptyBox.setPadding(new Insets(80, 0, 0, 0));
                        emptyBox.getChildren().addAll(errorIcon, noLyrics);
                        
                        lyricsContent.getChildren().add(emptyBox);
                    } else {
                        // 添加歌词行
                        int lineNumber = 0;
                        for (LyricLine line : parsedLyrics) {
                            lineNumber++;
                            
                            // 创建歌词行容器
                            HBox lineContainer = new HBox(15);
                            lineContainer.setAlignment(Pos.CENTER_LEFT);
                            lineContainer.setPadding(new Insets(5, 10, 5, 10));
                            
                            // 行号（仅显示有时间戳的行）
                            if (line.getTimeMs() > 0) {
                                Label timeLabel = new Label(formatLyricTime(line.getTimeMs()));
                                timeLabel.setStyle("-fx-text-fill: #888888; -fx-font-size: 14px; -fx-min-width: 45px;");
                                lineContainer.getChildren().add(timeLabel);
                            } else {
                                // 为没有时间戳的行添加空白，保持对齐
                                Region spacer = new Region();
                                spacer.setMinWidth(45);
                                lineContainer.getChildren().add(spacer);
                            }
                            
                            // 歌词文本
                            Label lyricLine = new Label(line.getText());
                            lyricLine.setStyle("-fx-text-fill: #e6e6e6; -fx-font-size: 18px;");
                            lyricLine.setWrapText(true);
                            HBox.setHgrow(lyricLine, Priority.ALWAYS);
                            
                            lineContainer.getChildren().add(lyricLine);
                            lyricsContent.getChildren().add(lineContainer);
                        }
                    }
                });
            } catch (Exception e) {
                log.error("加载歌词失败: " + e.getMessage(), e);
                // 回到JavaFX线程更新UI，显示错误信息
                Platform.runLater(() -> {
                    lyricsContent.getChildren().clear();
                    
                    Label errorLabel = new Label("加载歌词失败: " + e.getMessage());
                    errorLabel.setStyle("-fx-text-fill: #ff6666; -fx-font-style: italic; -fx-font-size: 16px;");
                    errorLabel.setWrapText(true);
                    
                    ImageView errorIcon = new ImageView(new Image("static/logo.png", 30, 30, true, true));
                    errorIcon.setOpacity(0.5);
                    
                    VBox errorBox = new VBox(20);
                    errorBox.setAlignment(Pos.CENTER);
                    errorBox.setPadding(new Insets(80, 0, 0, 0));
                    errorBox.getChildren().addAll(errorIcon, errorLabel);
                    
                    lyricsContent.getChildren().add(errorBox);
                });
            }
        }).start();
    }
    
    // 格式化歌词时间为 mm:ss 格式
    private String formatLyricTime(long timeMs) {
        int seconds = (int) (timeMs / 1000);
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    // 解析LRC格式歌词
    private void parseLrcFormat(String lyricsText) {
        parsedLyrics.clear();

        // 按行分割
        String[] lines = lyricsText.split("\n");
        Pattern timePattern = Pattern.compile("\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\]");

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) {
                continue;
            }

            Matcher matcher = timePattern.matcher(line);

            // 找到时间标记
            if (matcher.find()) {
                try {
                    int minutes = Integer.parseInt(matcher.group(1));
                    int seconds = Integer.parseInt(matcher.group(2));
                    int hundredths = Integer.parseInt(matcher.group(3));

                    // 计算毫秒时间
                    long timeMs = minutes * 60 * 1000 + seconds * 1000 + hundredths * 10;

                    // 提取歌词文本(去除时间标记)
                    String text = line.substring(matcher.end()).trim();
                    // 如果有多个时间标记，继续处理
                    while (matcher.find()) {
                        text = text.substring(matcher.end() - matcher.start()).trim();
                    }

                    // 添加到解析后的歌词列表
                    parsedLyrics.add(new LyricLine(text, timeMs));
                } catch (Exception e) {
                    log.warn("解析歌词行失败: " + line, e);
                }
            } else {
                // 没有时间标记的行，作为普通文本添加
                // 如果不是元信息（通常以[开头，如[ar:艺术家]）
                if (!line.startsWith("[") || !line.contains(":")) {
                    parsedLyrics.add(new LyricLine(line, 0));
                }
            }
        }

        // 按时间排序
        parsedLyrics.sort(Comparator.comparingLong(LyricLine::getTimeMs));
    }

    // 歌词行类
    private static class LyricLine {
        private final String text;
        private final long timeMs;

        public LyricLine(String text, long timeMs) {
            this.text = text;
            this.timeMs = timeMs;
        }

        public String getText() {
            return text;
        }

        public long getTimeMs() {
            return timeMs;
        }
    }

    // 从URL获取歌词内容的方法
    private String fetchLyricsFromUrl(String lrcUrl) throws IOException {
        URL url = new URL(lrcUrl);
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "GBK"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
        }

        return result.toString();
    }

    // 更新歌词视图
    private void updateLyricsView(SongsResp song) {
        if (lyricsView == null) {
            return;
        }

        // 获取BorderPane (现在第一个子元素是BorderPane)
        BorderPane lyricsBorderPane = (BorderPane) lyricsView.getChildren().get(0);
        
        // 获取左侧面板
        VBox leftPanel = (VBox) lyricsBorderPane.getLeft();
        
        // 更新封面图片
        StackPane imageContainer = (StackPane) leftPanel.getChildren().get(0);
        ImageView largeImageView = (ImageView) imageContainer.getChildren().get(0);
        if (song.getPicture() != null) {
            largeImageView.setImage(new Image(song.getPicture()));
        } else {
            largeImageView.setImage(new Image("static/default-cover.png"));
        }

        // 更新歌曲信息
        VBox songInfoBox = (VBox) leftPanel.getChildren().get(1);
        Label titleLabel = (Label) songInfoBox.getChildren().get(0);
        Label artistLabel = (Label) songInfoBox.getChildren().get(1);
        Label albumLabel = (Label) songInfoBox.getChildren().get(2);
        
        titleLabel.setText(song.getTitle());
        artistLabel.setText(song.getArtist());
        albumLabel.setText(song.getAlbum() != null ? song.getAlbum() : "");

        // 更新歌词 - 获取右侧面板
        VBox rightPanel = (VBox) lyricsBorderPane.getCenter();
        ScrollPane scrollPane = (ScrollPane) rightPanel.getChildren().get(1);
        VBox lyricsContent = (VBox) scrollPane.getContent();
        
        // 重置当前高亮索引
        currentHighlightIndex = -1;
        
        // 更新歌词内容
        updateLyricsContent(lyricsContent);
    }

    private VBox createBottomPlaylists() {
        VBox bottomPlaylists = new VBox(10);
        bottomPlaylists.setPadding(new Insets(5, 0, 10, 0));

        // 创建自定义样式的TabPane
        TabPane tabPane = new TabPane();
        tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE); // 禁用关闭按钮
        tabPane.getStyleClass().add("custom-tab-pane");
        tabPane.setStyle("-fx-background-color: transparent; -fx-tab-min-width: 80px;");

        // 自建歌单 Tab
        Tab selfCreatedTab = new Tab("自建歌单");
        ListView<PlaylistResp> selfCreatedList = new ListView<>();
        selfCreatedList.setStyle("-fx-background-color: #f8f8f8; -fx-background-radius: 5px;");
        
        // 从后端获取用户创建的歌单
        Result<List<PlaylistResp>> playlistResult = playlistController.queryByUserId();
        if (playlistResult.isSuccess() && playlistResult.getData() != null && !playlistResult.getData().isEmpty()) {
            List<PlaylistResp> playlists = playlistResult.getData();
            selfCreatedList.getItems().addAll(playlists);
        } else {
            // 创建一个空的PlaylistResp对象，显示"暂无歌单"
            PlaylistResp emptyPlaylist = new PlaylistResp();
            emptyPlaylist.setName("暂无歌单");
            selfCreatedList.getItems().add(emptyPlaylist);
        }
        
        // 自定义歌单列表样式
        selfCreatedList.setCellFactory(param -> new ListCell<PlaylistResp>() {
            @Override
            protected void updateItem(PlaylistResp playlist, boolean empty) {
                super.updateItem(playlist, empty);
                if (empty || playlist == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    HBox cellBox = new HBox(8);
                    cellBox.setPadding(new Insets(5));
                    cellBox.setAlignment(Pos.CENTER_LEFT);
                    
                    // 歌单图标
                    ImageView iconView = new ImageView(new Image("static/playlist-icon.png", 16, 16, true, true));
                    
                    // 歌单名称
                    Label nameLabel = new Label(playlist.getName());
                    nameLabel.setStyle("-fx-font-size: 13px;");
                    
                    cellBox.getChildren().addAll(iconView, nameLabel);
                    
                    // 悬停效果
                    cellBox.setOnMouseEntered(e -> {
                        cellBox.setStyle("-fx-background-color: #eaeaea; -fx-background-radius: 4px;");
                    });
                    
                    cellBox.setOnMouseExited(e -> {
                        cellBox.setStyle("-fx-background-color: transparent;");
                    });
                    
                    setGraphic(cellBox);
                    setText(null);
                }
            }
        });
        
        // 添加选择事件 - 点击歌单跳转到对应的歌单详情页
        selfCreatedList.setOnMouseClicked(event -> {
            PlaylistResp selectedPlaylist = selfCreatedList.getSelectionModel().getSelectedItem();
            if (selectedPlaylist != null && !selectedPlaylist.getName().equals("暂无歌单")) {
                // 显示歌单页面
                showPlaylistPage();
                
                // 在歌单页面中选中对应的歌单
                showSelectedPlaylist(selectedPlaylist);
            }
        });
        
        selfCreatedTab.setContent(selfCreatedList);

        // 收藏歌单 Tab
        Tab collectionTab = new Tab("收藏歌单");
        ListView<PlaylistResp> collectionList = new ListView<>();
        collectionList.setStyle("-fx-background-color: #f8f8f8; -fx-background-radius: 5px;");
        
        // 异步加载收藏的歌单列表
        new Thread(() -> {
            try {
                Result<List<PlaylistResp>> result = playlistCollectedController.queryCollectedPlaylist();
                
                Platform.runLater(() -> {
                    if (result.isSuccess() && result.getData() != null) {
                        List<PlaylistResp> collectedPlaylists = result.getData();
                        
                        if (!collectedPlaylists.isEmpty()) {
                            // 添加收藏的歌单到列表
                            collectionList.getItems().addAll(collectedPlaylists);
                        } else {
                            // 创建一个空的PlaylistResp对象，显示"暂无收藏歌单"
                            PlaylistResp emptyPlaylist = new PlaylistResp();
                            emptyPlaylist.setName("暂无收藏歌单");
                            collectionList.getItems().add(emptyPlaylist);
                        }
                    } else {
                        // 加载失败时显示错误提示
                        PlaylistResp errorPlaylist = new PlaylistResp();
                        errorPlaylist.setName("加载失败，点击重试");
                        collectionList.getItems().add(errorPlaylist);
                    }
                });
            } catch (Exception e) {
                log.error("加载收藏歌单列表失败", e);
                Platform.runLater(() -> {
                    PlaylistResp errorPlaylist = new PlaylistResp();
                    errorPlaylist.setName("加载失败，点击重试");
                    collectionList.getItems().add(errorPlaylist);
                });
            }
        }).start();
        
        // 自定义收藏歌单列表样式
        collectionList.setCellFactory(param -> new ListCell<PlaylistResp>() {
            @Override
            protected void updateItem(PlaylistResp playlist, boolean empty) {
                super.updateItem(playlist, empty);
                if (empty || playlist == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    HBox cellBox = new HBox(8);
                    cellBox.setPadding(new Insets(5));
                    cellBox.setAlignment(Pos.CENTER_LEFT);
                    
                    // 收藏歌单图标
                    ImageView iconView = new ImageView(new Image("static/heart-icon.png", 16, 16, true, true));
                    
                    // 歌单名称
                    Label nameLabel = new Label(playlist.getName());
                    nameLabel.setStyle("-fx-font-size: 13px;");
                    
                    cellBox.getChildren().addAll(iconView, nameLabel);
                    
                    // 悬停效果
                    cellBox.setOnMouseEntered(e -> {
                        if (!playlist.getName().equals("暂无收藏歌单") && !playlist.getName().equals("加载失败，点击重试")) {
                        cellBox.setStyle("-fx-background-color: #eaeaea; -fx-background-radius: 4px;");
                        }
                    });
                    
                    cellBox.setOnMouseExited(e -> {
                        cellBox.setStyle("-fx-background-color: transparent;");
                    });
                    
                    setGraphic(cellBox);
                    setText(null);
                }
            }
        });
        
        // 添加收藏歌单的点击事件
        collectionList.setOnMouseClicked(event -> {
            PlaylistResp selectedPlaylist = collectionList.getSelectionModel().getSelectedItem();
            if (selectedPlaylist != null && !selectedPlaylist.getName().equals("暂无收藏歌单") 
                    && !selectedPlaylist.getName().equals("加载失败，点击重试")) {
                // 显示选中的歌单详情
                showSelectedPlaylist(selectedPlaylist);
            } else if (selectedPlaylist != null && selectedPlaylist.getName().equals("加载失败，点击重试")) {
                // 点击错误提示时重新加载歌单
                collectionList.getItems().clear();
                
                // 显示加载中
                PlaylistResp loadingPlaylist = new PlaylistResp();
                loadingPlaylist.setName("正在加载...");
                collectionList.getItems().add(loadingPlaylist);
                
                // 重新加载收藏歌单
                new Thread(() -> {
                    try {
                        Result<List<PlaylistResp>> result = playlistCollectedController.queryCollectedPlaylist();
                        
                        Platform.runLater(() -> {
                            collectionList.getItems().clear();
                            
                            if (result.isSuccess() && result.getData() != null) {
                                List<PlaylistResp> collectedPlaylists = result.getData();
                                
                                if (!collectedPlaylists.isEmpty()) {
                                    collectionList.getItems().addAll(collectedPlaylists);
                                } else {
                                    PlaylistResp emptyPlaylist = new PlaylistResp();
                                    emptyPlaylist.setName("暂无收藏歌单");
                                    collectionList.getItems().add(emptyPlaylist);
                                }
                            } else {
                                PlaylistResp errorPlaylist = new PlaylistResp();
                                errorPlaylist.setName("加载失败，点击重试");
                                collectionList.getItems().add(errorPlaylist);
                            }
                        });
                    } catch (Exception e) {
                        log.error("重新加载收藏歌单列表失败", e);
                        Platform.runLater(() -> {
                            collectionList.getItems().clear();
                            PlaylistResp errorPlaylist = new PlaylistResp();
                            errorPlaylist.setName("加载失败，点击重试");
                            collectionList.getItems().add(errorPlaylist);
                        });
                    }
                }).start();
            }
        });
        
        collectionTab.setContent(collectionList);

        // 设置Tab样式
        selfCreatedTab.setStyle("-fx-background-color: transparent;");
        collectionTab.setStyle("-fx-background-color: transparent;");
        
        // 添加新建歌单按钮
        HBox actionBox = new HBox(10);
        actionBox.setPadding(new Insets(5));
        actionBox.setAlignment(Pos.CENTER_LEFT);
        
        Button addPlaylistButton = new Button("添加歌单");
        addPlaylistButton.setStyle(
            "-fx-background-color: transparent;" +
            "-fx-text-fill: #1db954;" +
            "-fx-font-size: 13px;" +
            "-fx-cursor: hand;"
        );
        
        ImageView addIcon = new ImageView(new Image("static/add-icon.png", 14, 14, true, true));
        addPlaylistButton.setGraphic(addIcon);
        addPlaylistButton.setGraphicTextGap(5);
        
        // 添加按钮点击事件
        addPlaylistButton.setOnAction(e -> {
            // 显示创建歌单对话框
            PlaylistUi tempPlaylistUi = new PlaylistUi(player, null, () -> {
                // 刷新左侧面板的歌单列表
                Platform.runLater(() -> {
                    // 重新创建左侧面板
                    VBox newLeftPanel = createLeftPanel();
                    
                    // 替换当前左侧面板
                    root.setLeft(newLeftPanel);
                    leftPanel = newLeftPanel;
                });
            });
            tempPlaylistUi.showCreatePlaylistDialog();
        });
        
        actionBox.getChildren().add(addPlaylistButton);

        // 添加 Tabs 到 TabPane
        tabPane.getTabs().addAll(selfCreatedTab, collectionTab);

        // 将 TabPane 和按钮添加到 VBox
        bottomPlaylists.getChildren().addAll(tabPane, actionBox);
        return bottomPlaylists;
    }

    // 添加新方法，用于在歌单页面中显示选中的歌单
    public void showSelectedPlaylist(PlaylistResp playlist) {
        // 先查询完整的歌单信息，以确保获取最新的歌单数据包括歌曲列表
        new Thread(() -> {
            try {
                // 查询完整的歌单信息
                Result<PlaylistResp> playlistResult = playlistController.queryById(playlist.getId());
                
                if (playlistResult.isSuccess() && playlistResult.getData() != null) {
                    // 获取完整的歌单信息
                    PlaylistResp completePlaylist = playlistResult.getData();
                    
                    // 在JavaFX线程中更新UI
                    Platform.runLater(() -> {
                        // 创建一个新的PlaylistUi实例，传入选中的歌单
                        PlaylistUi playlistUi = new PlaylistUi(player, 
                            // 歌单选择回调
                            new PlaylistUi.PlaylistSelectedCallback() {
                                @Override
                                public void onPlaylistSelected(PlaylistResp selectedPlaylist) {
                                    // 处理歌单选择事件
                                    log.info("选择歌单: {}", selectedPlaylist.getName());
                                    // 如果歌单有歌曲，可以播放第一首
                                    if (selectedPlaylist.getSongsRespList() != null && !selectedPlaylist.getSongsRespList().isEmpty()) {
                                        currentSong = selectedPlaylist.getSongsRespList().get(0);
                                        updateCurrentSongInfo(currentSong);
                                        player.play(currentSong.getFilePath());
                                    }
                                }

                                @Override
                                public void onSongSelected(SongsResp song) {
                                    // 单击歌曲时，更新当前歌曲信息到播放栏，但不播放
                                    currentSong = song;
                                    updateCurrentSongInfo(currentSong);
                                    log.info("选择歌曲: {}", song.getTitle());
                                }
                            },
                            // 歌单刷新回调
                            () -> {
                                // 刷新左侧面板的歌单列表
                                Platform.runLater(() -> {
                                    // 重新创建左侧面板
                                    VBox newLeftPanel = createLeftPanel();
                                    
                                    // 替换当前左侧面板
                                    root.setLeft(newLeftPanel);
                                    leftPanel = newLeftPanel;
                                });
                            }
                        );
                        
                        // 清空右侧面板
                        rightPanel.getChildren().clear();
                        
                        // 获取歌单页面并添加到右侧面板
                        VBox playlistPage = playlistUi.createPlaylistPage();
                        rightPanel.getChildren().add(playlistPage);
                        VBox.setVgrow(playlistPage, Priority.ALWAYS);
                        
                        // 在新打开的歌单页面中显示指定的歌单
                        playlistUi.showPlaylistDetail(completePlaylist);
                    });
                } else {
                    log.error("获取歌单详情失败: {}", playlistResult.getMessage());
                }
            } catch (Exception e) {
                log.error("查询歌单信息异常", e);
            }
        }).start();
    }

    // 启动主页刷新定时器
    private void startHomePageRefreshTimer() {
        // 停止已有的定时器
        stopHomePageRefreshTimer();
        
        // 立即刷新一次数据
        updateDaySongs();
        if (daySongsGrid != null) {
            Platform.runLater(this::refreshDaySongsGrid);
        }
        
        // 创建新的定时器，每1分钟刷新一次（更快的刷新频率）
        homePageRefreshTimeline = new Timeline(new KeyFrame(Duration.seconds(TimeConstant.TEN_SECONDS), event -> {
            // 获取新的每日推荐歌曲
            updateDaySongs();
            
            // 无论当前是否在主页，都更新数据，以便切换时显示最新内容
            Platform.runLater(this::refreshDaySongsGrid);
        }));
        
        homePageRefreshTimeline.setCycleCount(Timeline.INDEFINITE);
        homePageRefreshTimeline.play();
    }
    
    // 停止主页刷新定时器
    private void stopHomePageRefreshTimer() {
        if (homePageRefreshTimeline != null) {
            homePageRefreshTimeline.stop();
            homePageRefreshTimeline = null;
        }
    }
    
    // 获取最新的每日推荐歌曲
    private void updateDaySongs() {
        try {
            Result<List<SongsResp>> daySongsResult = songsController.getDaySongs();
            if (daySongsResult.isSuccess() && daySongsResult.getData() != null) {
                currentDaySongs = daySongsResult.getData();
            } else {
                log.warn("获取每日推荐歌曲失败: 未知错误");
            }
        } catch (Exception e) {
            log.error("获取每日推荐歌曲异常", e);
        }
    }
    
    // 刷新每日推荐的歌曲列表UI
    private void refreshDaySongsGrid() {
        if (daySongsGrid != null) {
            try {
                // 清除现有内容（保留表头）
                daySongsGrid.getChildren().removeIf(node -> GridPane.getRowIndex(node) != null && GridPane.getRowIndex(node) > 0);
                
                // 添加新的歌曲行
                if (!currentDaySongs.isEmpty()) {
                    for (int i = 0; i < currentDaySongs.size(); i++) {
                        addSongRowToGrid(daySongsGrid, currentDaySongs.get(i), i);
                    }
                } else {
                    // 如果没有歌曲，显示提示信息
                    Label noSongsLabel = new Label("暂无推荐歌曲，请稍后再试");
                    noSongsLabel.setStyle("-fx-text-fill: #808080; -fx-font-style: italic;");
                    GridPane.setColumnSpan(noSongsLabel, 4);
                    daySongsGrid.add(noSongsLabel, 0, 1);
                }
            } catch (Exception e) {
                log.error("刷新歌曲列表UI异常", e);
            }
        }
    }
    
    @Override
    public void init() throws Exception {
        // 初始化时立即获取数据
        try {
            updateDaySongs();
        } catch (Exception e) {
            log.error("初始化获取每日推荐歌曲失败", e);
        }
    }

    // 应用关闭时清理资源
    @Override 
    public void stop() {
        stopLyricUpdateTimer();
        stopHomePageRefreshTimer();
    }

    private VBox createRecommendedSongsList() {
        VBox container = new VBox(10);
        container.setPadding(new Insets(10, 0, 20, 0));
        
        // 创建表格式布局
        GridPane songsGrid = new GridPane();
        songsGrid.setHgap(15);
        songsGrid.setVgap(10);
        songsGrid.setPadding(new Insets(5));
        
        // 添加表头
        Label numberLabel = new Label("#");
        numberLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(numberLabel, 0, 0);
        
        Label titleLabel = new Label("歌曲");
        titleLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(titleLabel, 1, 0);
        
        Label artistLabel = new Label("歌手");
        artistLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(artistLabel, 2, 0);
        
        Label albumLabel = new Label("专辑");
        albumLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(albumLabel, 3, 0);
        
        Label durationLabel = new Label("时长");
        durationLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(durationLabel, 4, 0);
        
        // 添加喜欢表头
        Label likeLabel = new Label("喜欢");
        likeLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(likeLabel, 5, 0);
        GridPane.setHalignment(likeLabel, javafx.geometry.HPos.CENTER);
        
        // 添加到歌单表头
        Label addToPlaylistLabel = new Label("添加");
        addToPlaylistLabel.setStyle("-fx-font-weight: bold;");
        songsGrid.add(addToPlaylistLabel, 6, 0);
        GridPane.setHalignment(addToPlaylistLabel, javafx.geometry.HPos.CENTER);
        
        // 获取推荐歌曲数据
        List<SongsResp> recommendedSongs = getRecommendedSongs();
        
        // 添加歌曲行
        for (int i = 0; i < recommendedSongs.size(); i++) {
            addRecommendedSongRow(songsGrid, recommendedSongs.get(i), i);
        }
        
        // 设置列宽
        ColumnConstraints col1 = new ColumnConstraints(30);  // 序号列
        ColumnConstraints col2 = new ColumnConstraints(240); // 歌曲列
        ColumnConstraints col3 = new ColumnConstraints(140); // 歌手列
        ColumnConstraints col4 = new ColumnConstraints(180); // 专辑列
        ColumnConstraints col5 = new ColumnConstraints(60);  // 时长列
        ColumnConstraints col6 = new ColumnConstraints(50);  // 喜欢列
        ColumnConstraints col7 = new ColumnConstraints(50);  // 添加到歌单列
        songsGrid.getColumnConstraints().addAll(col1, col2, col3, col4, col5, col6, col7);
        
        // 添加"查看更多"按钮
        Button moreButton = new Button("查看更多");
        moreButton.setStyle("-fx-background-color: transparent; -fx-text-fill: #1db954; -fx-font-weight: bold;");
        moreButton.setOnAction(e -> {
            // TODO: 实现查看更多推荐歌曲的逻辑
            log.info("查看更多推荐歌曲");
        });
        
        HBox moreButtonBox = new HBox(moreButton);
        moreButtonBox.setAlignment(Pos.CENTER_RIGHT);
        moreButtonBox.setPadding(new Insets(10, 5, 0, 0));
        
        // 将表格和按钮添加到容器
        container.getChildren().addAll(songsGrid, moreButtonBox);
        
        return container;
    }
    
    private void addRecommendedSongRow(GridPane grid, SongsResp song, int index) {
        // 行背景 - 用于悬停效果
        HBox rowBackground = new HBox();
        rowBackground.setPrefHeight(50);
        rowBackground.setPrefWidth(700);
        GridPane.setColumnSpan(rowBackground, 7); // 扩展行背景跨度到7列，为喜欢按钮和添加到歌单按钮留出空间
        grid.add(rowBackground, 0, index + 1);
        
        // 序号
        Label number = new Label(String.valueOf(index + 1));
        number.setStyle("-fx-text-fill: #808080;");
        grid.add(number, 0, index + 1);
        
        // 歌曲（带封面）
        HBox songBox = new HBox(10);
        songBox.setAlignment(Pos.CENTER_LEFT);
        
        ImageView cover = new ImageView(new Image(song.getPicture(), 40, 40, true, true));
        
        VBox songInfo = new VBox(3);
        Label songTitle = new Label(song.getTitle());
        songTitle.setStyle("-fx-font-weight: bold;");
        songInfo.getChildren().add(songTitle);
        
        songBox.getChildren().addAll(cover, songInfo);
        grid.add(songBox, 1, index + 1);
        
        // 歌手
        Label artist = new Label(song.getArtist());
        artist.setStyle("-fx-text-fill: #404040;");
        grid.add(artist, 2, index + 1);
        
        // 专辑
        Label album = new Label(song.getAlbum());
        album.setStyle("-fx-text-fill: #606060;");
        album.setWrapText(true);
        grid.add(album, 3, index + 1);
        
        // 时长
        Label duration = new Label(formatDuration(song.getDuration()));
        duration.setStyle("-fx-text-fill: #808080;");
        grid.add(duration, 4, index + 1);
        
        // 喜欢按钮
        Button likeButton = new Button();
        likeButton.getStyleClass().add("like-button");
        likeButton.setStyle("-fx-background-color: transparent;");
        
        // 根据歌曲的isLiked属性设置按钮状态
        updateLikeButtonAppearance(likeButton, song.getIsLiked() != null && song.getIsLiked());
        
        // 添加点击事件
        likeButton.setOnAction(e -> {
            toggleLikeSong(likeButton, song);
        });
        
        // 添加到网格
        grid.add(likeButton, 5, index + 1);
        GridPane.setHalignment(likeButton, javafx.geometry.HPos.CENTER);
        
        // 添加到歌单按钮
        Button addToPlaylistButton = new Button();
        addToPlaylistButton.setStyle("-fx-background-color: transparent;");
        ImageView addIcon = new ImageView(new Image("static/add-to-playlist.png", 20, 20, true, true));
        addToPlaylistButton.setGraphic(addIcon);
        addToPlaylistButton.setTooltip(new Tooltip("添加到歌单"));
        
        // 添加点击事件
        addToPlaylistButton.setOnAction(e -> {
            showAddToPlaylistDialog(song);
        });
        
        // 添加到网格
        grid.add(addToPlaylistButton, 6, index + 1);
        GridPane.setHalignment(addToPlaylistButton, javafx.geometry.HPos.CENTER);
        
        // 添加鼠标悬停效果和点击事件
        rowBackground.setOnMouseEntered(e -> {
            rowBackground.setStyle("-fx-background-color: rgba(0,0,0,0.05);");
        });
        rowBackground.setOnMouseExited(e -> {
            rowBackground.setStyle("-fx-background-color: transparent;");
        });
        rowBackground.setOnMouseClicked(event -> {
            // 设置当前播放歌曲
            currentSong = song;
            updateCurrentSongInfo(currentSong);
            if (event.getClickCount() == 2) {
                log.info("播放歌曲: " + currentSong.getTitle());
                // 实际播放歌曲逻辑
                player.play(currentSong.getFilePath());
            }
        });
    }
    
    /**
     * 切换歌曲的喜欢状态
     */
    private void toggleLikeSong(Button likeButton, SongsResp song) {
        // 异步处理喜欢/取消喜欢操作
        new Thread(() -> {
            try {
                Result<Boolean> actionResult;
                boolean currentlyLiked = song.getIsLiked() != null && song.getIsLiked();
                
                if (currentlyLiked) {
                    // 如果当前已喜欢，则取消喜欢
                    actionResult = songsLikedController.unlike(song.getId());
                    log.info("取消喜欢歌曲: {}", song.getId());
                } else {
                    // 如果当前未喜欢，则添加喜欢
                    actionResult = songsLikedController.like(song.getId());
                    log.info("喜欢歌曲: {}", song.getId());
                }
                
                // 操作成功，更新按钮状态和歌曲喜欢状态
                if (actionResult.isSuccess()) {
                    // 更新歌曲对象的喜欢状态
                    song.setIsLiked(!currentlyLiked);
                    
                    Platform.runLater(() -> {
                        updateLikeButtonAppearance(likeButton, !currentlyLiked);
                    });
                }
            } catch (Exception e) {
                log.error("切换歌曲喜欢状态失败", e);
            }
        }).start();
    }
    
    private List<SongsResp> getRecommendedSongs() {
        // 尝试从后端获取推荐歌曲
        try {
            Result<List<SongsResp>> result = songsController.getRecommendSongs();
            if (result.isSuccess() && result.getData() != null) {
                return result.getData();
            }
            return Collections.emptyList();
        } catch (Exception e) {
            log.error("获取推荐歌曲失败", e);
            return Collections.emptyList();
        }
    }

    /**
     * 更新喜欢按钮的外观
     */
    private void updateLikeButtonAppearance(Button likeButton, boolean isLiked) {
        if (isLiked) {
            // 已喜欢状态
            likeButton.setGraphic(new ImageView(new Image("static/heart-filled.png", 20, 20, true, true)));
            likeButton.setTooltip(new Tooltip("取消喜欢"));
        } else {
            // 未喜欢状态
            likeButton.setGraphic(new ImageView(new Image("static/heart-icon.png", 20, 20, true, true)));
            likeButton.setTooltip(new Tooltip("喜欢"));
        }
    }

    // 添加showPersonalCenter方法
    private void showPersonalCenter() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();
            
            // 使用PersonalCenterUi类创建个人中心页面
            PersonalCenterUi personalCenterUi = new PersonalCenterUi(player, 
                // 歌曲选择回调
                song -> {
                // 当选择歌曲时更新当前歌曲信息
                            currentSong = song;
                            updateCurrentSongInfo(currentSong);
                },
                // 用户信息更新回调
                updatedUser -> {
                    // 更新左侧面板的用户信息
                    Platform.runLater(() -> {
                        // 重新创建左侧面板
                        VBox newLeftPanel = createLeftPanel();
                        
                        // 替换当前左侧面板
                        root.setLeft(newLeftPanel);
                        leftPanel = newLeftPanel;
                    });
                }
            );
            
            // 获取个人中心页面并添加到右侧面板
            VBox personalCenterPage = personalCenterUi.createPersonalCenter();
            rightPanel.getChildren().add(personalCenterPage);
            VBox.setVgrow(personalCenterPage, Priority.ALWAYS);
        }
    }

    public void showPlaylistPage() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();
            
            // 使用PlaylistUi类创建歌单页面
            PlaylistUi playlistUi = new PlaylistUi(player, 
                // 歌单选择回调
                new PlaylistUi.PlaylistSelectedCallback() {
                    @Override
                    public void onPlaylistSelected(PlaylistResp playlist) {
                        // 处理歌单选择事件
                        log.info("选择歌单: {}", playlist.getName());
                    }

                    @Override
                    public void onSongSelected(SongsResp song) {
                        // 单击歌曲时，更新当前歌曲信息到播放栏，但不播放
                        currentSong = song;
                        updateCurrentSongInfo(currentSong);
                        log.info("选择歌曲: {}", song.getTitle());
                    }
                },
                // 歌单刷新回调
                () -> {
                    // 刷新左侧面板的歌单列表
                    Platform.runLater(() -> {
                        // 重新创建左侧面板
                        VBox newLeftPanel = createLeftPanel();
                        
                        // 替换当前左侧面板
                        root.setLeft(newLeftPanel);
                        leftPanel = newLeftPanel;
                    });
                }
            );
            
            // 获取歌单页面并添加到右侧面板
            VBox playlistPage = playlistUi.createPlaylistPage();
            rightPanel.getChildren().add(playlistPage);
            VBox.setVgrow(playlistPage, Priority.ALWAYS);
        }
    }

    /**
     * 显示添加歌曲到歌单的对话框
     * @param song 要添加的歌曲
     */
    public void showAddToPlaylistDialog(SongsResp song) {
        // 创建对话框
        Stage dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.setTitle("添加到歌单");
        dialog.setWidth(400);
        dialog.setHeight(500);
        dialog.getIcons().add(new Image("static/logo.png"));
        
        VBox content = new VBox(15);
        content.setPadding(new Insets(20));
        content.setStyle("-fx-background-color: linear-gradient(to bottom, #f8f8f8, #ffffff);");
        
        // 标题
        Label titleLabel = new Label("选择要添加到的歌单");
        titleLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-text-fill: #333333;");
        
        // 歌曲信息
        HBox songInfoBox = new HBox(15);
        songInfoBox.setAlignment(Pos.CENTER_LEFT);
        songInfoBox.setPadding(new Insets(10));
        songInfoBox.setStyle("-fx-background-color: rgba(240, 240, 245, 0.6); -fx-background-radius: 8px;");
        
        // 歌曲封面（添加圆角）
        StackPane coverContainer = new StackPane();
        ImageView songCover = new ImageView(new Image(song.getPicture(), 60, 60, true, true));
        
        // 设置圆角
        Rectangle clip = new Rectangle(60, 60);
        clip.setArcWidth(10);
        clip.setArcHeight(10);
        songCover.setClip(clip);
        
        // 添加阴影效果
        songCover.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 5, 0, 0, 2);");
        coverContainer.getChildren().add(songCover);
        
        // 歌曲详情
        VBox songDetails = new VBox(5);
        songDetails.setAlignment(Pos.CENTER_LEFT);
        
        Label songTitle = new Label(song.getTitle());
        songTitle.setStyle("-fx-font-weight: bold; -fx-font-size: 16px;");
        
        Label artistName = new Label(song.getArtist());
        artistName.setStyle("-fx-text-fill: #666; -fx-font-size: 14px;");
        
        Label albumName = new Label(song.getAlbum() != null ? song.getAlbum() : "");
        albumName.setStyle("-fx-text-fill: #888; -fx-font-size: 12px; -fx-font-style: italic;");
        
        songDetails.getChildren().addAll(songTitle, artistName, albumName);
        
        songInfoBox.getChildren().addAll(coverContainer, songDetails);
        
        // 分隔线
        Separator separator = new Separator();
        separator.setStyle("-fx-opacity: 0.6;");
        
        // 提示文本
        Label promptLabel = new Label("选择一个歌单，将歌曲添加到其中");
        promptLabel.setStyle("-fx-text-fill: #666; -fx-font-size: 13px;");
        
        // 加载指示器（初始显示）
        ProgressIndicator loadingIndicator = new ProgressIndicator();
        loadingIndicator.setMaxSize(30, 30);
        
        // 歌单列表容器
        VBox playlistContainer = new VBox(10);
        playlistContainer.getChildren().add(loadingIndicator);
        VBox.setVgrow(playlistContainer, Priority.ALWAYS);
        
        // 歌单列表
        ListView<PlaylistResp> playlistListView = new ListView<>();
        playlistListView.setPrefHeight(300);
        playlistListView.setStyle("-fx-background-color: transparent; -fx-background-insets: 0; -fx-padding: 5;");
        VBox.setVgrow(playlistListView, Priority.ALWAYS);
        
        // 加载歌单列表
        new Thread(() -> {
            try {
                Result<List<PlaylistResp>> result = playlistController.queryByUserId();
                if (result.isSuccess() && result.getData() != null) {
                    Platform.runLater(() -> {
                        // 移除加载指示器
                        playlistContainer.getChildren().clear();
                        
                        // 添加歌单列表
                        playlistContainer.getChildren().add(playlistListView);
                        playlistListView.getItems().addAll(result.getData());
                        
                        // 如果没有歌单，显示提示
                        if (result.getData().isEmpty()) {
                            Label noPlaylistLabel = new Label("您还没有创建歌单，请先创建歌单");
                            noPlaylistLabel.setStyle("-fx-text-fill: #888; -fx-font-style: italic; -fx-alignment: center;");
                            playlistContainer.getChildren().clear();
                            playlistContainer.getChildren().add(noPlaylistLabel);
                        }
                    });
                } else {
                    Platform.runLater(() -> {
                        // 显示错误信息
                        Label errorLabel = new Label("加载歌单失败: " + result.getMessage());
                        errorLabel.setStyle("-fx-text-fill: #c00; -fx-font-style: italic;");
                        playlistContainer.getChildren().clear();
                        playlistContainer.getChildren().add(errorLabel);
                    });
                }
            } catch (Exception e) {
                log.error("加载歌单列表失败", e);
                Platform.runLater(() -> {
                    // 显示错误信息
                    Label errorLabel = new Label("加载歌单失败: " + e.getMessage());
                    errorLabel.setStyle("-fx-text-fill: #c00; -fx-font-style: italic;");
                    playlistContainer.getChildren().clear();
                    playlistContainer.getChildren().add(errorLabel);
                });
            }
        }).start();
        
        // 自定义歌单列表项
        playlistListView.setCellFactory(param -> new ListCell<PlaylistResp>() {
            @Override
            protected void updateItem(PlaylistResp playlist, boolean empty) {
                super.updateItem(playlist, empty);
                if (empty || playlist == null) {
                    setText(null);
                    setGraphic(null);
                    setStyle("-fx-background-color: transparent;");
                } else {
                    HBox cellBox = new HBox(12);
                    cellBox.setAlignment(Pos.CENTER_LEFT);
                    cellBox.setPadding(new Insets(8));
                    
                    // 歌单封面
                    StackPane coverPane = new StackPane();
                    ImageView coverView = new ImageView();
                    coverView.setFitWidth(50);
                    coverView.setFitHeight(50);
                    
                    // 设置圆角
                    Rectangle clipRect = new Rectangle(50, 50);
                    clipRect.setArcWidth(8);
                    clipRect.setArcHeight(8);
                    coverView.setClip(clipRect);
                    
                    if (playlist.getCoverUrl() != null && !playlist.getCoverUrl().isEmpty()) {
                        coverView.setImage(new Image(playlist.getCoverUrl()));
                    } else {
                        coverView.setImage(new Image("static/logo.png"));
                    }
                    
                    coverPane.getChildren().add(coverView);
                    
                    // 歌单信息
                    VBox infoBox = new VBox(3);
                    Label nameLabel = new Label(playlist.getName());
                    nameLabel.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
                    
                    Label countLabel = new Label(playlist.getSongsRespList() != null ? 
                            playlist.getSongsRespList().size() + " 首歌曲" : "0 首歌曲");
                    countLabel.setStyle("-fx-text-fill: #888; -fx-font-size: 12px;");
                    
                    infoBox.getChildren().addAll(nameLabel, countLabel);
                    
                    cellBox.getChildren().addAll(coverPane, infoBox);
                    setGraphic(cellBox);
                    setText(null);
                    
                    // 设置选中和悬停样式
                    if (isSelected()) {
                        cellBox.setStyle("-fx-background-color: #e8f4ff; -fx-background-radius: 6px;");
                    } else {
                        cellBox.setStyle("-fx-background-color: transparent;");
                        
                        // 添加悬停效果
                        setOnMouseEntered(e -> {
                            if (!isSelected()) {
                                cellBox.setStyle("-fx-background-color: #f5f5f5; -fx-background-radius: 6px;");
                            }
                        });
                        
                        setOnMouseExited(e -> {
                            if (!isSelected()) {
                                cellBox.setStyle("-fx-background-color: transparent;");
                            }
                        });
                    }
                }
            }
        });
        
        // 按钮区域
        HBox buttonBox = new HBox(10);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.setPadding(new Insets(15, 0, 0, 0));
        
        Button cancelButton = new Button("取消");
        cancelButton.setPrefWidth(80);
        cancelButton.setStyle("-fx-background-color: #f0f0f0; -fx-text-fill: #666; -fx-font-weight: normal; " +
                             "-fx-background-radius: 4px; -fx-padding: 8px 15px;");
        cancelButton.setOnAction(e -> dialog.close());
        
        // 添加悬停效果
        cancelButton.setOnMouseEntered(e -> 
            cancelButton.setStyle("-fx-background-color: #e0e0e0; -fx-text-fill: #666; -fx-font-weight: normal; " +
                                 "-fx-background-radius: 4px; -fx-padding: 8px 15px;")
        );
        cancelButton.setOnMouseExited(e -> 
            cancelButton.setStyle("-fx-background-color: #f0f0f0; -fx-text-fill: #666; -fx-font-weight: normal; " +
                                 "-fx-background-radius: 4px; -fx-padding: 8px 15px;")
        );
        
        Button addButton = new Button("添加");
        addButton.setPrefWidth(80);
        addButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold; " +
                          "-fx-background-radius: 4px; -fx-padding: 8px 15px;");
        addButton.setDisable(true); // 初始禁用，直到选择了歌单
        
        // 添加悬停效果
        addButton.setOnMouseEntered(e -> {
            if (!addButton.isDisabled()) {
                addButton.setStyle("-fx-background-color: #1ed760; -fx-text-fill: white; -fx-font-weight: bold; " +
                                  "-fx-background-radius: 4px; -fx-padding: 8px 15px;");
            }
        });
        addButton.setOnMouseExited(e -> {
            if (!addButton.isDisabled()) {
                addButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold; " +
                                  "-fx-background-radius: 4px; -fx-padding: 8px 15px;");
            }
        });
        
        // 监听歌单选择
        playlistListView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            addButton.setDisable(newVal == null);
        });
        
        // 添加按钮点击事件
        addButton.setOnAction(e -> {
            PlaylistResp selectedPlaylist = playlistListView.getSelectionModel().getSelectedItem();
            if (selectedPlaylist != null) {
                // 显示加载中状态
                addButton.setDisable(true);
                addButton.setText("处理中...");
                
                // 先检查歌曲是否已经存在于歌单中
                new Thread(() -> {
                    try {
                        Result<Boolean> checkResult = songsPlaylistController.checkSongExistsInPlaylist(
                                song.getId().intValue(), selectedPlaylist.getId().intValue());
                        
                        if (checkResult.isSuccess() && Boolean.TRUE.equals(checkResult.getData())) {
                            // 歌曲已存在于歌单中
                            Platform.runLater(() -> {
                                showAlert(Alert.AlertType.INFORMATION, "提示", 
                                        "歌曲「" + song.getTitle() + "」已经存在于歌单「" + selectedPlaylist.getName() + "」中");
                                addButton.setDisable(false);
                                addButton.setText("添加");
                            });
                            return;
                        }
                        
                        // 调用后端API添加歌曲到歌单
                        Result<Boolean> result = songsPlaylistController.addSong(
                                song.getId().intValue(), selectedPlaylist.getId().intValue());
                        
                        Platform.runLater(() -> {
                            if (result.isSuccess() && Boolean.TRUE.equals(result.getData())) {
                                // 显示成功提示
                                showAlert(Alert.AlertType.INFORMATION, "添加成功", 
                                        "歌曲「" + song.getTitle() + "」已添加到歌单「" + selectedPlaylist.getName() + "」");
                                dialog.close();
                            } else {
                                // 显示失败提示
                                showAlert(Alert.AlertType.ERROR, "添加失败", 
                                        "无法添加歌曲到歌单: " + (result.getMessage() != null ? result.getMessage() : "未知错误"));
                                addButton.setDisable(false);
                                addButton.setText("添加");
                            }
                        });
                    } catch (Exception ex) {
                        log.error("添加歌曲到歌单失败", ex);
                        Platform.runLater(() -> {
                            showAlert(Alert.AlertType.ERROR, "添加失败", "发生错误: " + ex.getMessage());
                            addButton.setDisable(false);
                            addButton.setText("添加");
                        });
                    }
                }).start();
            }
        });
        
        buttonBox.getChildren().addAll(cancelButton, addButton);
        
        // 组装内容
        content.getChildren().addAll(titleLabel, songInfoBox, separator, promptLabel, playlistContainer, buttonBox);
        
        Scene scene = new Scene(content);
        dialog.setScene(scene);
        dialog.showAndWait();
    }
    
    /**
     * 显示提示对话框
     */
    private void showAlert(Alert.AlertType alertType, String title, String message) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    /**
     * 显示所有歌单页面
     */
    private void showAllPlaylistsPage() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();
            
            // 创建内容容器
            VBox contentBox = new VBox(15);
            contentBox.setPadding(new Insets(10));
            
            // 标题和搜索区域
            HBox headerBox = new HBox(15);
            headerBox.setAlignment(Pos.CENTER_LEFT);
            headerBox.setPadding(new Insets(5, 0, 15, 0));
            
            Label titleLabel = new Label("发现歌单");
            titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
            
            Region spacer = new Region();
            HBox.setHgrow(spacer, Priority.ALWAYS);
            
            // 搜索框
            HBox searchBox = new HBox();
            searchBox.setStyle("-fx-background-color: #e6e6e6; -fx-background-radius: 15px;");
            searchBox.setPadding(new Insets(5, 10, 5, 10));
            searchBox.setAlignment(Pos.CENTER_LEFT);
            
            // 搜索图标
            ImageView searchIcon = new ImageView(new Image("static/search-icon.png", 16, 16, true, true));
            
            // 搜索输入框
            TextField searchField = new TextField();
            searchField.setPromptText("搜索歌单");
            searchField.setPrefWidth(200);
            searchField.setStyle("-fx-background-color: transparent; -fx-border-color: transparent;");
            
            searchBox.getChildren().addAll(searchIcon, searchField);
            
            headerBox.getChildren().addAll(titleLabel, spacer, searchBox);
            
            // 创建加载指示器
            ProgressIndicator loadingIndicator = new ProgressIndicator();
            loadingIndicator.setMaxSize(50, 50);
            
            // 歌单网格容器
            GridPane playlistsGrid = new GridPane();
            playlistsGrid.setHgap(20);
            playlistsGrid.setVgap(25);
            
            // 添加加载指示器
            VBox loadingBox = new VBox(loadingIndicator);
            loadingBox.setAlignment(Pos.CENTER);
            loadingBox.setPadding(new Insets(50, 0, 0, 0));
            
            // 添加到内容容器
            contentBox.getChildren().addAll(headerBox, new Separator(), loadingBox);
            
            // 创建滚动面板
            ScrollPane scrollPane = new ScrollPane(contentBox);
            scrollPane.setFitToWidth(true);
            scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
            scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
            scrollPane.getStyleClass().add("edge-to-edge");
            scrollPane.setStyle("-fx-background-color: transparent;");
            
            // 添加到右侧面板
            rightPanel.getChildren().add(scrollPane);
            VBox.setVgrow(scrollPane, Priority.ALWAYS);
            
            // 异步加载所有歌单
            new Thread(() -> {
                try {
                    Result<List<PlaylistResp>> result = playlistController.queryAll();
                    
                    Platform.runLater(() -> {
                        // 移除加载指示器
                        contentBox.getChildren().remove(loadingBox);
                        
                        if (result.isSuccess() && result.getData() != null) {
                            List<PlaylistResp> playlists = result.getData();
                            
                            if (!playlists.isEmpty()) {
                                // 创建歌单网格
                                int column = 0;
                                int row = 0;
                                
                                for (PlaylistResp playlist : playlists) {
                                    VBox playlistCard = createAllPlaylistCard(playlist);
                                    playlistsGrid.add(playlistCard, column, row);
                                    
                                    column++;
                                    if (column >= 4) {  // 每行显示5个歌单
                                        column = 0;
                                        row++;
                                    }
                                }
                                
                                contentBox.getChildren().add(playlistsGrid);
                            } else {
                                // 没有歌单
                                Label emptyLabel = new Label("暂无歌单");
                                emptyLabel.setStyle("-fx-text-fill: #999; -fx-font-size: 16px;");
                                
                                VBox emptyBox = new VBox(emptyLabel);
                                emptyBox.setAlignment(Pos.CENTER);
                                emptyBox.setPadding(new Insets(50, 0, 0, 0));
                                
                                contentBox.getChildren().add(emptyBox);
                            }
                        } else {
                            // 加载失败
                            Label errorLabel = new Label("加载歌单失败: " + result.getMessage());
                            errorLabel.setStyle("-fx-text-fill: #c00; -fx-font-size: 16px;");
                            
                            VBox errorBox = new VBox(errorLabel);
                            errorBox.setAlignment(Pos.CENTER);
                            errorBox.setPadding(new Insets(50, 0, 0, 0));
                            
                            contentBox.getChildren().add(errorBox);
                        }
                    });
                } catch (Exception e) {
                    log.error("加载所有歌单失败", e);
                    
                    Platform.runLater(() -> {
                        // 移除加载指示器
                        contentBox.getChildren().remove(loadingBox);
                        
                        // 显示错误信息
                        Label errorLabel = new Label("加载歌单失败: " + e.getMessage());
                        errorLabel.setStyle("-fx-text-fill: #c00; -fx-font-size: 16px;");
                        
                        VBox errorBox = new VBox(errorLabel);
                        errorBox.setAlignment(Pos.CENTER);
                        errorBox.setPadding(new Insets(50, 0, 0, 0));
                        
                        contentBox.getChildren().add(errorBox);
                    });
                }
            }).start();
        }
    }

    /**
     * 创建显示在"发现歌单"页面中的歌单卡片
     */
    private VBox createAllPlaylistCard(PlaylistResp playlist) {
        VBox card = new VBox(5);
        card.setPrefWidth(180);
        card.setPadding(new Insets(5));
        card.setCursor(Cursor.HAND);
        
        // 鼠标悬停效果
        card.setOnMouseEntered(e -> card.setStyle("-fx-background-color: #f5f5f5; -fx-background-radius: 8px;"));
        card.setOnMouseExited(e -> card.setStyle("-fx-background-color: transparent;"));

        // 创建歌单封面的StackPane（包含图片和操作按钮）
        StackPane coverPane = new StackPane();
        
        // 歌单封面图片
        ImageView coverImage = new ImageView();
        coverImage.setFitWidth(180);
        coverImage.setFitHeight(180);
        
        // 设置圆角
        Rectangle clip = new Rectangle(180, 180);
        clip.setArcWidth(15);
        clip.setArcHeight(15);
        coverImage.setClip(clip);
        
        // 设置封面图片
        if (playlist.getCoverUrl() != null && !playlist.getCoverUrl().isEmpty()) {
            coverImage.setImage(new Image(playlist.getCoverUrl()));
        } else {
            coverImage.setImage(new Image("static/default-cover.png"));
        }
        
        // 添加阴影效果
        coverImage.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 5);");
        
        // 操作按钮背景（半透明黑色背景）
        Rectangle actionBg = new Rectangle(180, 50);
        actionBg.setFill(Color.rgb(0, 0, 0, 0.6));
        actionBg.setOpacity(0); // 初始隐藏
        
        // 操作按钮容器
        HBox actionBox = new HBox(15);
        actionBox.setAlignment(Pos.CENTER);
        actionBox.setPadding(new Insets(0, 10, 0, 10));
        actionBox.setOpacity(0); // 初始隐藏
        
        // 播放按钮
        Button playButton = new Button();
        playButton.setStyle("-fx-background-color: #1db954; -fx-background-radius: 50%;");
        ImageView playIcon = new ImageView(new Image("static/pause-icon.png", 16, 16, true, true));
        playButton.setGraphic(playIcon);
        playButton.setTooltip(new Tooltip("播放歌单"));
        
        // 收藏按钮 - 根据isCollected字段设置不同的样式
        Button collectButton = new Button();
        
        // 检查歌单是否已被收藏
        boolean isCollected = playlist.getIsCollected() != null && playlist.getIsCollected();
        
        if (isCollected) {
            // 已收藏状态
            collectButton.setStyle("-fx-background-color: #ff7700; -fx-background-radius: 50%;");
            ImageView heartIcon = new ImageView(new Image("static/heart-filled.png", 16, 16, true, true));
            collectButton.setGraphic(heartIcon);
            collectButton.setTooltip(new Tooltip("取消收藏"));
        } else {
            // 未收藏状态
            collectButton.setStyle("-fx-background-color: white; -fx-background-radius: 50%;");
            ImageView collectIcon = new ImageView(new Image("static/add-to-playlist.png", 16, 16, true, true));
            collectButton.setGraphic(collectIcon);
            collectButton.setTooltip(new Tooltip("收藏歌单"));
        }
        
        // 添加操作按钮
        actionBox.getChildren().addAll(playButton, collectButton);
        
        // 将按钮和背景添加到封面容器
        coverPane.getChildren().addAll(coverImage, actionBg, actionBox);
        StackPane.setAlignment(actionBg, Pos.BOTTOM_CENTER);
        StackPane.setAlignment(actionBox, Pos.BOTTOM_CENTER);
        
        // 鼠标悬停时显示操作按钮
        coverPane.setOnMouseEntered(e -> {
            actionBg.setOpacity(1);
            actionBox.setOpacity(1);
        });
        
        coverPane.setOnMouseExited(e -> {
            actionBg.setOpacity(0);
            actionBox.setOpacity(0);
        });
        
        // 歌单名称
        Label nameLabel = new Label(playlist.getName());
        nameLabel.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
        nameLabel.setWrapText(true);
        nameLabel.setPrefWidth(180);
        nameLabel.setMaxWidth(180);
        
        // 创建者信息
        Label creatorLabel = new Label("创建者: " + (playlist.getCreatedByName() != null ? playlist.getCreatedByName() : "未知用户"));
        creatorLabel.setStyle("-fx-text-fill: #666666; -fx-font-size: 12px;");
        
        // 歌单介绍
        String description = playlist.getDescription();
        if (description == null || description.trim().isEmpty()) {
            description = "暂无介绍";
        }
        // 如果介绍太长则截断
        if (description.length() > 60) {
            description = description.substring(0, 60) + "...";
        }
        
        Label descriptionLabel = new Label(description);
        descriptionLabel.setStyle("-fx-text-fill: #999999; -fx-font-size: 12px;");
        descriptionLabel.setWrapText(true);
        descriptionLabel.setPrefWidth(180);
        descriptionLabel.setMaxHeight(40); // 限制高度，防止介绍过长
        
        // 添加组件到卡片
        card.getChildren().addAll(coverPane, nameLabel, creatorLabel, descriptionLabel);
        
        // 点击卡片显示歌单详情
        card.setOnMouseClicked(e -> {
            showSelectedPlaylist(playlist);
        });
        
        // 播放按钮点击事件
        playButton.setOnAction(e -> {
            e.consume(); // 阻止事件冒泡
            if (playlist.getSongsRespList() != null && !playlist.getSongsRespList().isEmpty()) {
                // 获取完整歌单信息并播放第一首歌
                new Thread(() -> {
                    try {
                        Result<PlaylistResp> playlistResult = playlistController.queryById(playlist.getId());
                        if (playlistResult.isSuccess() && playlistResult.getData() != null) {
                            PlaylistResp completePlaylist = playlistResult.getData();
                            if (completePlaylist.getSongsRespList() != null && !completePlaylist.getSongsRespList().isEmpty()) {
                                Platform.runLater(() -> {
                                    SongsResp firstSong = completePlaylist.getSongsRespList().get(0);
                                    currentSong = firstSong;
                                    updateCurrentSongInfo(currentSong);
                                    player.play(firstSong.getFilePath());
                                });
                            }
                        }
                    } catch (Exception ex) {
                        log.error("播放歌单失败", ex);
                    }
                }).start();
            }
        });
        
        // 收藏按钮点击事件
        collectButton.setOnAction(e -> {
            e.consume(); // 阻止事件冒泡
            
            // 根据当前收藏状态执行不同的操作
            if (isCollected) {
                // 如果已收藏，则执行取消收藏
                uncollectPlaylist(collectButton, Math.toIntExact(playlist.getId()));
            } else {
                // 如果未收藏，则执行收藏
                collectPlaylist(collectButton, Math.toIntExact(playlist.getId()));
            }
        });
        
        return card;
    }

    /**
     * 收藏歌单
     */
    private void collectPlaylist(Button collectButton, Integer playlistId) {
        // 显示加载状态
        collectButton.setDisable(true);
        
        // 引入PlaylistCollectedController
        PlaylistCollectedController playlistCollectedController = SpringContextUtil.getBean(PlaylistCollectedController.class);
        
        // 异步处理收藏操作
        new Thread(() -> {
            try {
                // 执行收藏操作
                Result<Boolean> result = playlistCollectedController.collect(playlistId);
                log.info("收藏歌单: {}, 结果: {}", playlistId, result.isSuccess());
                
                Platform.runLater(() -> {
                    if (result.isSuccess() && Boolean.TRUE.equals(result.getData())) {
                        // 更新按钮样式为已收藏
                        collectButton.setStyle("-fx-background-color: #ff7700; -fx-background-radius: 50%;");
                        ImageView heartIcon = new ImageView(new Image("static/heart-filled.png", 16, 16, true, true));
                        collectButton.setGraphic(heartIcon);
                        collectButton.setTooltip(new Tooltip("取消收藏"));
                        
                        // 收藏成功提示
                        showAlert(Alert.AlertType.INFORMATION, "收藏成功", "歌单已成功添加到你的收藏");
                        
                        // 重新启用按钮，但更改点击行为为取消收藏
                        collectButton.setDisable(false);
                        collectButton.setOnAction(e -> {
                            e.consume();
                            uncollectPlaylist(collectButton, playlistId);
                        });
                        
                        // 刷新左侧菜单的收藏歌单列表
                        refreshCollectedPlaylistsInLeftPanel();
                    } else {
                        // 恢复按钮状态
                        collectButton.setDisable(false);
                        
                        // 显示错误信息
                        showAlert(Alert.AlertType.ERROR, "收藏失败", 
                                result.getMessage() != null ? result.getMessage() : "收藏歌单失败，请稍后再试");
                    }
                });
            } catch (Exception e) {
                log.error("收藏歌单失败", e);
                
                Platform.runLater(() -> {
                    // 恢复按钮状态
                    collectButton.setDisable(false);
                    
                    // 显示错误信息
                    showAlert(Alert.AlertType.ERROR, "收藏失败", "发生错误: " + e.getMessage());
                });
            }
        }).start();
    }
    
    /**
     * 取消收藏歌单
     */
    private void uncollectPlaylist(Button collectButton, Integer playlistId) {
        // 显示加载状态
        collectButton.setDisable(true);
        
        // 引入PlaylistCollectedController
        PlaylistCollectedController playlistCollectedController = SpringContextUtil.getBean(PlaylistCollectedController.class);
        
        // 异步处理取消收藏操作
        new Thread(() -> {
            try {
                // 执行取消收藏操作
                Result<Boolean> result = playlistCollectedController.unCollect(playlistId);
                log.info("取消收藏歌单: {}, 结果: {}", playlistId, result.isSuccess());
                
                Platform.runLater(() -> {
                    if (result.isSuccess() && Boolean.TRUE.equals(result.getData())) {
                        // 更新按钮样式为未收藏
                        collectButton.setStyle("-fx-background-color: white; -fx-background-radius: 50%;");
                        ImageView addIcon = new ImageView(new Image("static/add-to-playlist.png", 16, 16, true, true));
                        collectButton.setGraphic(addIcon);
                        collectButton.setTooltip(new Tooltip("收藏歌单"));
                        
                        // 取消收藏成功提示
                        showAlert(Alert.AlertType.INFORMATION, "取消收藏", "已取消收藏该歌单");
                        
                        // 重新启用按钮，但更改点击行为为收藏
                        collectButton.setDisable(false);
                        collectButton.setOnAction(e -> {
                            e.consume();
                            collectPlaylist(collectButton, playlistId);
                        });
                        
                        // 刷新左侧菜单的收藏歌单列表
                        refreshCollectedPlaylistsInLeftPanel();
                    } else {
                        // 恢复按钮状态
                        collectButton.setDisable(false);
                        
                        // 显示错误信息
                        showAlert(Alert.AlertType.ERROR, "取消收藏失败", 
                                result.getMessage() != null ? result.getMessage() : "取消收藏歌单失败，请稍后再试");
                    }
                });
            } catch (Exception e) {
                log.error("取消收藏歌单失败", e);
                
                Platform.runLater(() -> {
                    // 恢复按钮状态
                    collectButton.setDisable(false);
                    
                    // 显示错误信息
                    showAlert(Alert.AlertType.ERROR, "取消收藏失败", "发生错误: " + e.getMessage());
                });
            }
        }).start();
    }

    /**
     * 刷新左侧菜单的收藏歌单列表
     */
    private void refreshCollectedPlaylistsInLeftPanel() {
        // 寻找TabPane和收藏歌单列表
        if (leftPanel != null) {
            // 遍历左侧面板寻找TabPane
            for (javafx.scene.Node node : leftPanel.getChildren()) {
                if (node instanceof VBox && ((VBox) node).getChildren().size() > 0) {
                    VBox bottomPlaylists = (VBox) node;
                    
                    // 查找TabPane
                    for (javafx.scene.Node childNode : bottomPlaylists.getChildren()) {
                        if (childNode instanceof TabPane) {
                            TabPane tabPane = (TabPane) childNode;
                            
                            // 查找收藏歌单Tab
                            for (Tab tab : tabPane.getTabs()) {
                                if (tab.getText().equals("收藏歌单") && tab.getContent() instanceof ListView) {
                                    // 找到收藏歌单列表
                                    @SuppressWarnings("unchecked")
                                    ListView<PlaylistResp> collectionList = (ListView<PlaylistResp>) tab.getContent();
                                    
                                    // 清空并重新加载列表
                                    collectionList.getItems().clear();
                                    
                                    // 显示加载中
                                    PlaylistResp loadingPlaylist = new PlaylistResp();
                                    loadingPlaylist.setName("正在加载...");
                                    collectionList.getItems().add(loadingPlaylist);
                                    
                                    // 异步重新加载收藏歌单
                                    new Thread(() -> {
                                        try {
                                            Result<List<PlaylistResp>> result = playlistCollectedController.queryCollectedPlaylist();
                                            
                                            Platform.runLater(() -> {
                                                collectionList.getItems().clear();
                                                
                                                if (result.isSuccess() && result.getData() != null) {
                                                    List<PlaylistResp> collectedPlaylists = result.getData();
                                                    
                                                    if (!collectedPlaylists.isEmpty()) {
                                                        collectionList.getItems().addAll(collectedPlaylists);
                                                    } else {
                                                        PlaylistResp emptyPlaylist = new PlaylistResp();
                                                        emptyPlaylist.setName("暂无收藏歌单");
                                                        collectionList.getItems().add(emptyPlaylist);
                                                    }
                                                } else {
                                                    PlaylistResp errorPlaylist = new PlaylistResp();
                                                    errorPlaylist.setName("加载失败，点击重试");
                                                    collectionList.getItems().add(errorPlaylist);
                                                }
                                            });
                                        } catch (Exception e) {
                                            log.error("重新加载收藏歌单列表失败", e);
                                            Platform.runLater(() -> {
                                                collectionList.getItems().clear();
                                                PlaylistResp errorPlaylist = new PlaylistResp();
                                                errorPlaylist.setName("加载失败，点击重试");
                                                collectionList.getItems().add(errorPlaylist);
                                            });
                                        }
                                    }).start();
                                    
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // 如果找不到收藏歌单列表，则重建左侧面板
        Platform.runLater(() -> {
            // 重新创建左侧面板
            VBox newLeftPanel = createLeftPanel();
            
            // 替换当前左侧面板
            root.setLeft(newLeftPanel);
            leftPanel = newLeftPanel;
        });
    }

    /**
     * 从PlaylistResp对象创建推荐歌单卡片
     */
    private VBox createRecommendationCardFromPlaylist(PlaylistResp playlist) {
        VBox card = new VBox(5);
        card.setPrefWidth(150);
        card.setCursor(Cursor.HAND);

        // 歌单封面
        ImageView imageView = new ImageView();
        imageView.setFitWidth(150);
        imageView.setFitHeight(150);
        
        // 设置封面图片
        if (playlist.getCoverUrl() != null && !playlist.getCoverUrl().isEmpty()) {
            imageView.setImage(new Image(playlist.getCoverUrl()));
        } else {
            imageView.setImage(new Image("static/default-cover.png"));
        }

        // 圆角效果
        Rectangle clip = new Rectangle(150, 150);
        clip.setArcWidth(10);
        clip.setArcHeight(10);
        imageView.setClip(clip);
        
        // 阴影效果
        imageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 0);");

        // 歌单标题
        Label titleLabel = new Label(playlist.getName());
        titleLabel.setStyle("-fx-font-weight: bold;");
        titleLabel.setWrapText(true);
        titleLabel.setPrefWidth(150);

        // 歌单描述
        String description = playlist.getDescription();
        if (description == null || description.trim().isEmpty()) {
            description = "暂无描述";
        }
        // 如果描述太长则截断
        if (description.length() > 50) {
            description = description.substring(0, 50) + "...";
        }
        
        Label descLabel = new Label(description);
        descLabel.setStyle("-fx-text-fill: #808080; -fx-font-size: 12px;");
        descLabel.setWrapText(true);
        descLabel.setPrefWidth(150);
        descLabel.setMaxHeight(40); // 限制高度

        card.getChildren().addAll(imageView, titleLabel, descLabel);

        // 添加点击事件 - 点击跳转到歌单详情
        card.setOnMouseClicked(event -> {
            showSelectedPlaylist(playlist);
        });
        
        // 悬停效果
        card.setOnMouseEntered(e -> {
            imageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(29,185,84,0.3), 12, 0, 0, 0);");
        });
        card.setOnMouseExited(e -> {
            imageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 10, 0, 0, 0);");
        });

        return card;
    }

    /**
     * 刷新推荐歌单
     */
    private void refreshRecommendPlaylists() {
        // 找到主内容区域的推荐歌单容器
        if (rightPanel != null && rightPanel.getChildren().size() > 0) {
            javafx.scene.Node firstChild = rightPanel.getChildren().get(0);
            if (firstChild instanceof ScrollPane) {
                ScrollPane scrollPane = (ScrollPane) firstChild;
                if (scrollPane.getContent() instanceof VBox) {
                    VBox contentBox = (VBox) scrollPane.getContent();
                    
                    // 找到水平滚动容器的位置
                    for (int i = 0; i < contentBox.getChildren().size(); i++) {
                        if (contentBox.getChildren().get(i) instanceof StackPane) {
                            StackPane horizontalScroller = (StackPane) contentBox.getChildren().get(i);
                            
                            // 重新创建推荐歌单滚动区并替换现有的
                            StackPane newHorizontalScroller = createHorizontalScroller();
                            contentBox.getChildren().set(i, newHorizontalScroller);
                            return;
                        }
                    }
                }
            }
        }
        
        // 如果找不到推荐歌单容器，则刷新整个主页
        showHomePage();
    }

    /**
     * 更新循环按钮图标和提示文本
     * @param repeatButton 循环按钮
     * @param mode 循环模式 (0: 列表循环, 1: 单曲循环, 2: 随机播放)
     */
    private void updateRepeatButtonIcon(Button repeatButton, int mode) {
        ImageView icon;
        String tooltipText;
        
        switch (mode) {
            case 1: // 单曲循环
                // 使用自定义的单曲循环图标
                icon = new ImageView(new Image("static/repeat-one-icon.png", 20, 20, true, true));
                tooltipText = "单曲循环";
                icon.setOpacity(1.0); // 高亮显示
                break;
            case 2: // 随机播放
                icon = new ImageView(new Image("static/shuffle-icon.png", 20, 20, true, true));
                tooltipText = "随机播放";
                icon.setOpacity(1.0); // 高亮显示
                break;
            default: // 列表循环
                icon = new ImageView(new Image("static/reservation_repeat_icon.png", 20, 20, true, true));
                tooltipText = "列表循环";
                icon.setOpacity(0.7); // 默认透明度
                break;
        }
        
        // 更新按钮图标
        repeatButton.setGraphic(icon);
        
        // 更新提示文本
        repeatButton.setTooltip(new Tooltip(tooltipText));
    }

    /**
     * 根据当前播放列表和索引更新当前歌曲信息
     */
    private void updateCurrentSongFromPlaylist() {
        int currentIndex = player.getCurrentIndex();
        List<String> playlist = player.getPlaylist();
        
        if (currentIndex >= 0 && currentIndex < playlist.size()) {
            String filePath = playlist.get(currentIndex);
            
            // 从数据库中获取歌曲信息
            try {
                // 根据文件路径查询歌曲信息
                Result<SongsResp> result = songsController.querySongByPath(filePath);
                if (result.isSuccess() && result.getData() != null) {
                    // 更新当前歌曲和UI
                    currentSong = result.getData();
                    updateCurrentSongInfo(currentSong);
                } else {
                    log.warn("无法获取歌曲信息: {}", filePath);
                }
            } catch (Exception e) {
                log.error("获取歌曲信息失败", e);
            }
        }
    }

    // 当前聊天会话ID
    private String currentChatId = null;
    
    /**
     * 生成6位随机会话ID
     */
    private String generateChatId() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
    
    /**
     * 显示AI聊天页面
     */
    private void showAiChatPage() {
        if (rightPanel != null) {
            rightPanel.getChildren().clear();
            
            // 创建内容容器
            BorderPane mainContainer = new BorderPane();
            
            // 创建左侧会话列表面板
            VBox sessionsPanel = new VBox(10);
            sessionsPanel.setPadding(new Insets(15));
            sessionsPanel.setPrefWidth(200);
            sessionsPanel.setStyle("-fx-background-color: #f5f5f7; -fx-background-radius: 10px;");
            
            // 会话列表标题
            Label sessionsTitle = new Label("会话列表");
            sessionsTitle.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            
            // 创建新会话按钮
            Button newSessionButton = new Button("新建会话");
            newSessionButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold; -fx-background-radius: 5px; -fx-font-size: 14px; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            newSessionButton.setPrefWidth(180);
            
            // 会话列表
            ListView<String> sessionListView = new ListView<>();
            sessionListView.setStyle("-fx-background-color: transparent; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            VBox.setVgrow(sessionListView, Priority.ALWAYS);
            
            // 加载会话列表
            loadChatSessions(sessionListView);
            
            // 组装左侧面板
            sessionsPanel.getChildren().addAll(sessionsTitle, newSessionButton, new Separator(), sessionListView);
            
            // 创建右侧聊天面板
            VBox chatPanel = new VBox(15);
            chatPanel.setPadding(new Insets(20));
            
            // 标题
            Label titleLabel = new Label("AI音乐助手");
            titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            
            // 当前会话ID显示
            Label chatIdLabel = new Label("当前无会话");
            chatIdLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            
            // 聊天历史区域
            VBox chatHistoryBox = new VBox(10);
            chatHistoryBox.setPadding(new Insets(15));
            chatHistoryBox.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 10, 0, 0, 0);");
            
            // 使用ScrollPane包装聊天历史，以便支持滚动
            ScrollPane chatScrollPane = new ScrollPane(chatHistoryBox);
            chatScrollPane.setFitToWidth(true);
            chatScrollPane.setStyle("-fx-background-color: transparent; -fx-background: transparent; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            chatScrollPane.setPrefHeight(500);
            VBox.setVgrow(chatScrollPane, Priority.ALWAYS);
            
            // 初始欢迎消息
            addAiMessage(chatHistoryBox, "你好！我是你的AI音乐助手，请先创建或选择一个会话开始聊天。");
            
            // 输入区域
            HBox inputBox = new HBox(10);
            inputBox.setAlignment(Pos.CENTER);
            
            // 文本输入框
            TextField inputField = new TextField();
            inputField.setPromptText("请输入你的问题...");
            inputField.setPrefHeight(40);
            inputField.setStyle("-fx-font-size: 16px; -fx-background-radius: 20px; -fx-padding: 5 15; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            inputField.setDisable(true);
            HBox.setHgrow(inputField, Priority.ALWAYS);
            
            // 发送按钮
            Button sendButton = new Button("发送");
            sendButton.setPrefHeight(40);
            sendButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold; -fx-background-radius: 20px; -fx-padding: 5 20; -fx-font-size: 16px; -fx-font-family: 'Microsoft YaHei', Arial, sans-serif;");
            sendButton.setDisable(true);
            
            // 处理发送消息
            EventHandler<ActionEvent> sendMessageHandler = event -> {
                if (currentChatId == null) {
                    showAlert(Alert.AlertType.WARNING, "提示", "请先创建或选择一个会话");
                    return;
                }
                
                String message = new String(inputField.getText().trim().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
                if (!message.isEmpty()) {
                    // 添加用户消息到聊天区域
                    addUserMessage(chatHistoryBox, message);
                    
                    // 清空输入框
                    inputField.clear();
                    
                    // 显示AI正在思考的状态
                    ProgressIndicator thinkingIndicator = new ProgressIndicator();
                    thinkingIndicator.setMaxSize(20, 20);
                    Label thinkingLabel = new Label("思考中...");
                    thinkingLabel.setStyle("-fx-font-family: 'Microsoft YaHei', Arial, sans-serif; -fx-font-size: 16px;");
                    HBox thinkingBox = new HBox(10, thinkingIndicator, thinkingLabel);
                    thinkingBox.setAlignment(Pos.CENTER_LEFT);
                    thinkingBox.setPadding(new Insets(10, 15, 10, 15));
                    thinkingBox.setStyle("-fx-background-color: #f0f0f0; -fx-background-radius: 15px; -fx-max-width: 120px;");
                    
                    HBox aiMessageContainer = new HBox(thinkingBox);
                    aiMessageContainer.setAlignment(Pos.CENTER_LEFT);
                    chatHistoryBox.getChildren().add(aiMessageContainer);
                    
                    // 自动滚动到底部
                    chatScrollPane.setVvalue(1.0);
                    
                    // 异步调用AI接口获取回复
                    new Thread(() -> {
                        try {
                            // 创建聊天请求
                            ChatReq chatReq = new ChatReq();
                            chatReq.setMessage(message);
                            chatReq.setChatId(currentChatId);
                            
                            // 调用后端接口获取AI回复
                            Result<String> result = chatController.chatWithChatId(chatReq);
                            
                            // 在JavaFX线程中更新UI
                            Platform.runLater(() -> {
                                // 移除"思考中"状态
                                chatHistoryBox.getChildren().remove(aiMessageContainer);
                                
                                if (result.isSuccess()) {
                                    // 添加AI回复
                                    addAiMessage(chatHistoryBox, result.getData());
                                } else {
                                    // 添加错误消息
                                    addAiMessage(chatHistoryBox, "抱歉，我遇到了一些问题，无法回答你的问题。");
                                }
                                
                                // 自动滚动到底部
                                chatScrollPane.setVvalue(1.0);
                            });
                        } catch (Exception e) {
                            log.error("获取AI回复失败", e);
                            
                            // 在JavaFX线程中更新UI
                            Platform.runLater(() -> {
                                // 移除"思考中"状态
                                chatHistoryBox.getChildren().remove(aiMessageContainer);
                                
                                // 添加错误消息
                                addAiMessage(chatHistoryBox, "抱歉，发生了错误，无法获取回复。");
                                
                                // 自动滚动到底部
                                chatScrollPane.setVvalue(1.0);
                            });
                        }
                    }).start();
                }
            };
            
            // 为发送按钮添加点击事件
            sendButton.setOnAction(sendMessageHandler);
            
            // 为输入框添加回车键事件
            inputField.setOnAction(sendMessageHandler);
            
            // 新建会话按钮点击事件
            newSessionButton.setOnAction(e -> {
                // 生成新的会话ID
                currentChatId = generateChatId();
                
                // 更新UI
                chatIdLabel.setText("会话ID: " + currentChatId);
                
                // 清空聊天历史
                chatHistoryBox.getChildren().clear();
                
                // 添加欢迎消息
                addAiMessage(chatHistoryBox, "已创建新会话（ID: " + currentChatId + "），请开始提问吧！");
                
                // 启用输入框和发送按钮
                inputField.setDisable(false);
                sendButton.setDisable(false);
                
                // 刷新会话列表
                loadChatSessions(sessionListView);
                
                // 设置输入框焦点
                inputField.requestFocus();
            });
            
            // 会话列表选择事件
            sessionListView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
                if (newVal != null) {
                    // 设置当前会话ID
                    currentChatId = newVal;
                    
                    // 更新UI
                    chatIdLabel.setText("会话ID: " + currentChatId);
                    
                    // 清空聊天历史
                    chatHistoryBox.getChildren().clear();
                    
                    // 加载历史会话消息
                    loadChatHistory(chatHistoryBox, currentChatId);
                    
                    // 启用输入框和发送按钮
                    inputField.setDisable(false);
                    sendButton.setDisable(false);
                }
            });
            
            // 组装输入区域
            inputBox.getChildren().addAll(inputField, sendButton);
            
            // 组装右侧面板
            chatPanel.getChildren().addAll(titleLabel, chatIdLabel, chatScrollPane, inputBox);
            
            // 组装主面板
            mainContainer.setLeft(sessionsPanel);
            mainContainer.setCenter(chatPanel);
            
            // 添加到右侧面板
            rightPanel.getChildren().add(mainContainer);
            VBox.setVgrow(mainContainer, Priority.ALWAYS);
        }
    }
    
    /**
     * 加载会话列表
     */
    private void loadChatSessions(ListView<String> sessionListView) {
        // 清空列表
        sessionListView.getItems().clear();
        
        // 异步加载会话列表
        new Thread(() -> {
            try {
                Result<List<String>> result = SpringContextUtil.getBean(ChatHistoryController.class).getChatIds();
                
                Platform.runLater(() -> {
                    if (result.isSuccess() && result.getData() != null) {
                        List<String> chatIds = result.getData();
                        if (!chatIds.isEmpty()) {
                            sessionListView.getItems().addAll(chatIds);
                        } else {
                            sessionListView.getItems().add("暂无会话");
                            sessionListView.setDisable(true);
                        }
                    } else {
                        sessionListView.getItems().add("加载失败");
                        sessionListView.setDisable(true);
                    }
                });
            } catch (Exception e) {
                log.error("加载会话列表失败", e);
                
                Platform.runLater(() -> {
                    sessionListView.getItems().add("加载失败");
                    sessionListView.setDisable(true);
                });
            }
        }).start();
    }
    
    /**
     * 加载历史会话消息
     */
    private void loadChatHistory(VBox chatHistoryBox, String chatId) {
        // 显示加载中
        ProgressIndicator loadingIndicator = new ProgressIndicator();
        loadingIndicator.setMaxSize(30, 30);
        
        HBox loadingBox = new HBox(loadingIndicator, new Label("加载历史消息中..."));
        loadingBox.setAlignment(Pos.CENTER);
        loadingBox.setSpacing(10);
        
        chatHistoryBox.getChildren().add(loadingBox);
        
        // 异步加载历史消息
        new Thread(() -> {
            try {
                Result<List<MsgResp>> result = SpringContextUtil.getBean(ChatHistoryController.class).getChatHistory(chatId);
                
                Platform.runLater(() -> {
                    // 移除加载提示
                    chatHistoryBox.getChildren().remove(loadingBox);
                    
                    if (result != null && result.isSuccess() && result.getData() != null) {
                        List<MsgResp> messages = result.getData();
                        
                        if (!messages.isEmpty()) {
                            for (MsgResp msg : messages) {
                                if ("user".equals(msg.getRole())) {
                                    addUserMessage(chatHistoryBox, msg.getContent());
                                } else if ("assistant".equals(msg.getRole())) {
                                    addAiMessage(chatHistoryBox, msg.getContent());
                                }
                            }
                        } else {
                            // 添加提示消息
                            addAiMessage(chatHistoryBox, "这是一个新的会话，请开始提问吧！");
                        }
                    } else {
                        // 添加错误消息
                        addAiMessage(chatHistoryBox, "无法加载历史消息，这可能是一个新的会话。");
                    }
                });
            } catch (Exception e) {
                log.error("加载历史消息失败", e);
                
                Platform.runLater(() -> {
                    // 移除加载提示
                    chatHistoryBox.getChildren().remove(loadingBox);
                    
                    // 添加错误消息
                    addAiMessage(chatHistoryBox, "加载历史消息失败，请重试。");
                });
            }
        }).start();
    }
    
    /**
     * 添加用户消息到聊天区域
     */
    private void addUserMessage(VBox chatHistoryBox, String message) {
        // 获取当前用户头像
        ImageView userAvatar = new ImageView();
        userAvatar.setFitWidth(30);
        userAvatar.setFitHeight(30);
        
        // 尝试获取用户头像
        Result<UsersResp> currentUserInfo = usersController.getCurrentUserInfo();
        String avatarPath = "static/default-avatar.png";
        
        if (currentUserInfo.isSuccess() && currentUserInfo.getData() != null) {
            UsersResp currentUser = currentUserInfo.getData();
            // 如果有头像，则使用用户头像
            if (currentUser.getAvatar() != null && !currentUser.getAvatar().isEmpty()) {
                avatarPath = currentUser.getAvatar();
            }
        }
        
        userAvatar.setImage(new Image(avatarPath));
        
        // 创建圆形裁剪
        Circle clip = new Circle(15, 15, 15);
        userAvatar.setClip(clip);
        
        // 创建文本标签
        Label messageLabel = new Label(message);
        messageLabel.setWrapText(true);
        messageLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: white; -fx-font-weight: normal;");
        
        // 创建消息气泡
        VBox messageBubble = new VBox(messageLabel);
        messageBubble.setPadding(new Insets(10, 15, 10, 15));
        messageBubble.setStyle("-fx-background-color: #1db954; -fx-background-radius: 15px 0px 15px 15px;");
        messageBubble.setMaxWidth(500);
        
        // 创建消息容器（右对齐，包含头像）
        HBox messageContainer = new HBox(10, messageBubble, userAvatar);
        messageContainer.setAlignment(Pos.CENTER_RIGHT);
        messageContainer.setPadding(new Insets(5, 0, 5, 0));
        
        // 添加到聊天历史
        chatHistoryBox.getChildren().add(messageContainer);
    }
    
    /**
     * 添加AI消息到聊天区域
     */
    private void addAiMessage(VBox chatHistoryBox, String message) {
        // 创建AI头像
        ImageView aiAvatar = new ImageView(new Image("static/logo.png"));
        aiAvatar.setFitWidth(30);
        aiAvatar.setFitHeight(30);
        
        // 创建圆形裁剪
        Circle clip = new Circle(15, 15, 15);
        aiAvatar.setClip(clip);
        
        // 添加边框效果
        StackPane avatarContainer = new StackPane();
        Circle border = new Circle(15, 15, 16);
        border.setFill(Color.TRANSPARENT);
        border.setStroke(Color.web("#1db954"));
        border.setStrokeWidth(1.5);
        avatarContainer.getChildren().addAll(aiAvatar, border);
        
        // 创建文本标签
        Label messageLabel = new Label(message);
        messageLabel.setWrapText(true);
        messageLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #333333; -fx-font-weight: normal;");
        
        // 创建消息气泡
        VBox messageBubble = new VBox(messageLabel);
        messageBubble.setPadding(new Insets(10, 15, 10, 15));
        messageBubble.setStyle("-fx-background-color: #f0f0f0; -fx-background-radius: 0px 15px 15px 15px;");
        messageBubble.setMaxWidth(500);
        
        // 创建消息容器（左对齐，包含头像）
        HBox messageContainer = new HBox(10, avatarContainer, messageBubble);
        messageContainer.setAlignment(Pos.CENTER_LEFT);
        messageContainer.setPadding(new Insets(5, 0, 5, 0));
        
        // 添加到聊天历史
        chatHistoryBox.getChildren().add(messageContainer);
    }

}

